Thursday, June 25, 2009

How to Retain the Insertion Order in a Map


Use LinkedHashMap to retain

Map map = new LinkedHashMap();
// Add some elements
map.put("a", new Integer(1));
map.put("b", new Integer(2));
map.put("c", new Integer(3));

// List the entries
for (Iterator it=map.keySet().iterator(); it.hasNext(); ) {
Object key = it.next();
Object value = map.get(key);
}
// [a=1, b=2, c=3]

How to Iterate the Map


// Iterate over the keys in the map
Iterator it = map.keySet().iterator();
while (it.hasNext()) {
// Get key
Object key = it.next();
}

// Iterate over the values in the map
it = map.values().iterator();
while (it.hasNext()) {
// Get value
Object value = it.next();
}

How to Remove the Entry from the Map


// Create a hash map
Map map = new HashMap();

// Add key/value pairs to the map
map.put("a", new Integer(1));
map.put("b", new Integer(2));
map.put("c", new Integer(3));

// remove method returns the value of removed key
oldValue = map.remove("c"); // 3

How to Create a Map


Map is a list of key-value pairs

// Create a hash map
Map map = new HashMap();

// Add key/value pairs to the map
map.put("a", new Integer(1));
map.put("b", new Integer(2));
map.put("c", new Integer(3));

How to Use Sorted Set


Elements in the TreeSet will automatically be arranged in sorted form.

// Create the sorted set
Set set = new TreeSet();

// Add elements to the set
set.add("b");
set.add("c");
set.add("a");

//[a,b,C]

How to Retain the Insertion Order in a Set


Use LinkedHashSet to retain the insertion order

Set set = new LinkedHashSet();

// Add some elements
set.add("1");
set.add("2");
set.add("3");
set.add("1");

// Iterate the set
for (Iterator it=set.iterator(); it.hasNext(); ) {
Object o = it.next();
}
// [1, 2, 3]

How to Add and Remove One Set to Another


// Create the sets
Set set1 = new HashSet();
Set set2 = new HashSet();

set1.add("A");
set2.add("A");
set2.add("B");

// set1=set1+set2-common elements
set1.addAll(set2); // set1=["A","B"]

// set1=set1-set2
set1.removeAll(set2); // set1=[]
 

Sample Java Codes Copyright © 2008 Green Scrapbook Diary Designed by SimplyWP | Made free by Scrapbooking Software | Bloggerized by Ipiet Notez