Collections in Java (0)

January 30th, 2009 by Frank Niedermann, under Java.

Collections in Java enable grouping of Objects and therefore help to manage data.

collection

Definition:

  • List: Sequence and identification with Int-keys (0, 1, 2, 3, …), duplicate values possible
  • Set: No duplicates allowed
  • Map: Key-Value assignment, duplicate values possible (not for keys)
  • Queue: Ordered data, Insertion/Extraction from Beginning/End

Some useful methods with Lists and Sets:

  • int size()
  • boolean isEmpty()
  • boolean add(Object o)
  • boolean remove(Object o)
  • int indexOf(Object o)
  • int lastIndexOf(Object o)
  • void clear()

Some useful methods with Maps:

  • Object get(Object key)
  • Object put(Object key, Object value)
  • Object remove(Object key)
  • int size()
  • Set keySet() -> Set with all keys (no duplicates)

List example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
List<String> list = new ArrayList<String>();
list.add("one");
list.add("two");
list.add("three");
list.remove(1);
list.add("four");
list.add(0, "zero");
 
for (int i=0; i<list.size(); i++) {
	System.out.println(list.get(i));
}
 
Iterator<String> listItr = list.iterator();
while (listItr.hasNext()) {
	System.out.println(listItr.next());
}
 
// last element
list.get(list.size()-1);

Set example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
HashSet<Integer> set = new HashSet<Integer>();
set.add(1);
set.add(2);
set.add(3);
set.add(2); // duplicate -> will be ignored
 
Iterator<Integer> setItr = set.iterator();
while (setItr.hasNext()) {
	System.out.println(setItr.next());
}
 
SortedSet<String> sortedSet = new TreeSet<String>();
sortedSet.add("Gamma");
sortedSet.add("Alpha");
sortedSet.add("Beta");
 
Iterator<String> sortedSetItr = sortedSet.iterator();
while (sortedSetItr.hasNext()) {
	System.out.println(sortedSetItr.next());
}

Map example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
HashMap<String, String> map = new HashMap<String, String>();
map.put("stable", "Etch");
map.put("testing", "Lenny");
map.put("unstable", "Sid");
 
for (String key : map.keySet()) {
	System.out.println(key + " is " + map.get(key));
}
 
Iterator<String> mapItr = map.keySet().iterator();
while (mapItr.hasNext()) {
	String key = (String) mapItr.next();
	System.out.println(key + " is " + (String)map.get(key));
}
 
// Sorted Map
TreeMap<String, String> sortedMap = new TreeMap<String, String>();
sortedMap.put("8.04", "Hardy Heron");
sortedMap.put("7.10", "Gutsy Gibbon");
sortedMap.put("9.04", "Jaunty Jackalope");
sortedMap.put("8.10", "Intrepid Ibex");
 
Iterator<String> sortedMapItr = sortedMap.keySet().iterator();
while (sortedMapItr.hasNext()) {
	String key = (String) sortedMapItr.next();
	System.out.println(key + " xis " + (String)sortedMap.get(key));
}

Tagged with , , , , .

Leave a Comment