HashMap in java can be sorted using its key or value. Lets see an example.
package learningscenarios;
/**
*
* @author Raghu
*/
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
public class SortingHash {
static Map myMap = new HashMap();
static HashMap map = new LinkedHashMap();
/**
* setting values for hashmap
*/
static void sethash() {
myMap.put("E", 5);
myMap.put("B", 2);
myMap.put("A", 1);
myMap.put("D", 4);
myMap.put("C", 3);
}
public static void main(String a[]) {
sethash();
sortKey();
sortValue();
}
/**
* Sorting hashmap with key
*/
static void sortKey() {
SortedSet<String> sortedset = new TreeSet<String>(myMap.keySet());
Iterator<String> it = sortedset.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}
}
/**
* Sorting hashmap with value
*/
static void sortValue() {
List yourMapKeys = new ArrayList(myMap.keySet());
List yourMapValues = new ArrayList(myMap.values());
TreeSet sortedSet = new TreeSet(yourMapValues);
Object[] sortedArray = sortedSet.toArray();
int size = sortedArray.length;
System.out.println("---------------");
for (int i = 0; i < size; i++) {
System.out.println((Integer) sortedArray[i]);
}
for (int i = 0; i < size; i++) {
map.put(yourMapKeys.get(yourMapValues.indexOf(sortedArray[i])),
sortedArray[i]);
}
Set ref = map.keySet();
Iterator it = ref.iterator();
System.out.println("---------------");
while (it.hasNext()) {
System.out.println((String) it.next());
}
}
}
9/3/10
Subscribe to:
Post Comments (Atom)
Popular Posts
-
Hi folks, I got a chance to work with JSF, it was an interesting requirement. Its about a custom component which would be of more use to ...
-
Hi Folks, I would like to share my another POC task in JSF with you all. "Primefaces Dropdown with Pagination & Filter "...
-
We shall create temp table in mysql using the sql script CREATE TEMPORARY TABLE testraghu(name VARCHAR(50) , phone VARCHAR(50)) Let us se...
-
Hi all, i would like to share a simple example of storing haspmap in mysql db. In order to store object into your db, the field type must ...
This code but it needs to be udpated to use Generics. Here is an example of How to sort HashMap in Java by keys and values which uses generics
ReplyDeleteThis code but it needs to be udpated to use Generics. Here is an example of How to sort HashMap in Java by keys and values which uses generics
ReplyDelete