Usefully Java code Snippets (2)

evertwagenaar.com logo

Thank you!

Part 1 was a  great success. So we will continue this series. In this part we will concentrate on the java.util package and in particular the Collections framework.

Summary

Java.util contains the collections framework, legacy collection classes, event model, date and time facilities, internationalization, and miscellaneous utility classes (a string tokenizer, a random-number generator, and a bit array).

1. Collections – map values to Objects

//A HashMap impliments the Map Interface 

Map map = new Hashmap();
map.add("key1", SomeObject);
map.add("key2", SomeOtherObject);
map.add("key3", SomeObject2);
map.add("key4", SomeOtherObject2);
  1. Create a dynamic list of Objects
//The ArrayList impliments the List Interface

List list = new ArrayList();
list.add(Object1);
list.add(Object2);
list.add(Object3);
list.add(Object4);
  1. Iterating over a Collection
// For a set or list
for (Iterator it=collection.iterator(); it.hasNext(); ) {
    Object element = it.next();
}

// For keys of a Map
for (Iterator it=map.keySet().iterator(); it.hasNext(); ) {
    Object key = it.next();
}

// For values of a map
for (Iterator it=map.values().iterator(); it.hasNext(); ) {
    Object value = it.next();
}

// For both the keys and values of a map
for (Iterator it=map.entrySet().iterator(); it.hasNext(); ) {
    Map.Entry entry = (Map.Entry)it.next();
    Object key = entry.getKey();
    Object value = entry.getValue();
}

Please note that this is Java 1.4 notation. Your compiler will probably complain  that the types should be set. It will however run since Java is downward compatible.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.