Check here and read about java.util package
Shuffling the Elements of a List or Array
Use Collections.shuffle() to randomly reorder the elements in a list.
// Create a list
List list = new ArrayList();
// Add elements to list
// Shuffle the elements in the list
Collections.shuffle(list);
// Create an array
String[] array = new String[]{“a”, “b”, “c”};
// Shuffle the elements in the array
Collections.shuffle(Arrays.asList(array));
Converting a Collection to an Array// Create an array containing the elements in a list
Object[] objectArray = list.toArray();
MyClass[] array = (MyClass[])list.toArray(new MyClass[list.size()]);// Create an array containing the elements in a set
objectArray = set.toArray();
array = (MyClass[])set.toArray(new MyClass[set.size()]);
// Create an array containing the keys in a map
objectArray = map.keySet().toArray();
array = (MyClass[])map.keySet().toArray(new MyClass[set.size()]);
// Create an array containing the values in a map
objectArray = map.values().toArray();
array = (MyClass[])map.values().toArray(new MyClass[set.size()]);
Converting an Array to a Collection// Fixed-size list
List list = Arrays.asList(array);// Growable list
list = new LinkedList(Arrays.asList(array));
// Duplicate elements are discarded
Set set = new HashSet(Arrays.asList(array));
Implementing a QueueLinkedList queue = new LinkedList();// Add to end of queue
queue.add(object);
// Get head of queue
Object o = queue.removeFirst();
// If the queue is to be used by multiple threads,
// the queue must be wrapped with code to synchronize the methods
queue = (LinkedList)Collections.synchronizedList(queue);
Implementing a StackLinkedList stack = new LinkedList();// Push on top of stack
stack.addFirst(object);
// Pop off top of stack
Object o = stack.getFirst();
// If the queue is to be used by multiple threads,
// the queue must be wrapped with code to synchronize the methods
stack = (LinkedList)Collections.synchronizedList(stack);
Listing the Elements of a CollectionThis example demonstrates how to iterate over the elements of various types of collections.// 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();
}
Storing Primitive Types in a CollectionCollections can only store objects, not primitive types like int and double. Primitive types must be placed in a wrapper object before they can be placed in a collection. This example demonstrates the storing of int values in a Map.// Create map
Map map = new HashMap();
// Create int wrapper object
Integer refInt = new Integer(123);
// Store int in map
map.put(“key”, refInt);
// Get int value from map
refInt = (Integer)map.get(“key”);
// Get the integer value from wrapper object
int i = refInt.intValue();
Creating a Copy of a CollectionThese examples create a shallow copy of a collection. That is, the new collection contains references to same objects as the source collection; the objects are not cloned.List stuff = Arrays.asList(new String[]{“a”, “b”});
// Make a copy of a list
List list = new ArrayList(stuff);
List list2 = new LinkedList(list);
// Make a copy of a set
Set set = new HashSet(stuff);
Set set2 = new TreeSet(set);
// Make a copy of a map
Map map = new HashMap();
// Add key/value pairs …
Map map2 = new TreeMap(map);
Making a Collection Read-OnlyMaking a collection read-only involves wrapping the collection in another object whose mutation methods all throw UnsupportedOperationException.List stuff = Arrays.asList(new String[]{“a”, “b”});
// Make a list read-only
List list = new ArrayList(stuff);
list = Collections.unmodifiableList(list);
try {
// Try modifying the list
list.set(0, “new value”);
} catch (UnsupportedOperationException e) {
// Can’t modify
}
// Make a set read-only
Set set = new HashSet(stuff);
set = Collections.unmodifiableSet(set);
// Make a map read-only
Map map = new HashMap();
// Add key/value pairs …
map = Collections.unmodifiableMap(map);
Creating a List// Create the list
List list = new LinkedList(); // Doubly-linked list
list = new ArrayList(); // List implemented as growable array// Append an element to the list
list.add(“a”);
// Insert an element at the head of the list
list.add(0, “b”);
// Get the number of elements in the list
int size = list.size(); // 2
// Retrieving the element at the end of the list
Object element = list.get(list.size()-1); // a
// Retrieving the element at the head of the list
element = list.get(0); // b
// Remove the first occurrence of an element
boolean b = list.remove(“b”); // true
b = list.remove(“b”); // false
// Remove the element at a particular index
element = list.remove(0); // a
Sorting a List// Create a list
String[] strArray = new String[] {“z”, “a”, “C”};
List list = Arrays.asList(strArray);// Sort
Collections.sort(list);
// C, a, z
// Case-insensitive sort
Collections.sort(list, String.CASE_INSENSITIVE_ORDER);
// a, C, z
// Reverse-order sort
Collections.sort(list, Collections.reverseOrder());
// z, a, C
// Case-insensitive reverse-order sort
Collections.sort(list, String.CASE_INSENSITIVE_ORDER);
Collections.reverse(list);
// z, C, a
Operating on Lists// Create the lists
List list1 = new ArrayList();
List list2 = new ArrayList();// Add elements to the lists …
// Copy all the elements from list2 to list1 (list1 += list2)
// list1 becomes the union of list1 and list2
list1.addAll(list2);
// Remove all the elements in list1 from list2 (list1 -= list2)
// list1 becomes the asymmetric difference of list1 and list2
list1.removeAll(list2);
// Get the intersection of list1 and list2
// list1 becomes the intersection of list1 and list2
list1.retainAll(list2);
// Remove all elements from a list
list1.clear();
// Truncate the list
int newSize = 2;
list1.subList(newSize, list1.size()).clear();
Creating a SetA set is a collection that holds unique values. Adding a value that’s already in the set has no effect.// Create the set
Set set = new HashSet();// Add elements to the set
set.add(“a”);
set.add(“b”);
set.add(“c”);
// Remove elements from the set
set.remove(“c”);
// Get number of elements in set
int size = set.size(); // 2
// Adding an element that already exists in the set has no effect
set.add(“a”);
size = set.size(); // 2
// Determining if an element is in the set
boolean b = set.contains(“a”); // true
b = set.contains(“c”); // false
// Iterating over the elements in the set
Iterator it = set.iterator();
while (it.hasNext()) {
// Get element
Object element = it.next();
}
// Create an array containing the elements in the set (in this case a String array)
String[] array = (String[])set.toArray(new String[set.size()]);
Operating on Sets // Create the sets
Set set1 = new HashSet();
Set set2 = new HashSet();// Add elements to the sets …// Copy all the elements from set2 to set1 (set1 += set2)
// set1 becomes the union of set1 and set2
set1.addAll(set2);
// Remove all the elements in set1 from set2 (set1 -= set2)
// set1 becomes the asymmetric difference of set1 and set2
set1.removeAll(set2);
// Get the intersection of set1 and set2
// set1 becomes the intersection of set1 and set2
set1.retainAll(set2);
// Remove all elements from a set
set1.clear();
Creating a Set That Retains Order-of-InsertionSet set = new LinkedHashSet();// Add some elements
set.add(“1″);
set.add(“2″);
set.add(“3″);
set.add(“2″);
// List the elements
for (Iterator it=set.iterator(); it.hasNext(); ) {
Object o = it.next();
}
// [1, 2, 3]
Creating a Hash TableA hash table, or map, holds key/value pairs.// Create a hash table
Map map = new HashMap(); // hash table
map = new TreeMap(); // sorted map
// 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));
// Get number of entries in map
int size = map.size(); // 2
// Adding an entry whose key exists in the map causes
// the new value to replace the old value
Object oldValue = map.put(“a”, new Integer(9)); // 1
// Remove an entry from the map and return the value of the removed entry
oldValue = map.remove(“c”); // 3
// 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();
}
Creating a Map That Retains Order-of-InsertionMap map = new LinkedHashMap();// Add some elements
map.put(“1″, “value1″);
map.put(“2″, “value2″);
map.put(“3″, “value3″);
map.put(“2″, “value4″);
// List the entries
for (Iterator it=map.keySet().iterator(); it.hasNext(); ) {
Object key = it.next();
Object value = map.get(key);
}
// [1=value1, 2=value4, 3=value3]
Creating a Sorted SetA sorted set is a set that maintains its items in a sorted order. Inserts and retrievals are more expensive in a sorted set but iterations over the set is always in order.
// Create the sorted set
SortedSet set = new TreeSet();
// Add elements to the set
set.add(“b”);
set.add(“c”);
set.add(“a”);
// Iterating over the elements in the set
Iterator it = set.iterator();
while (it.hasNext()) {
// Get element
Object element = it.next();
}
// The elements are iterated in order: a, b, c
// Create an array containing the elements in a set (in this case a String array).
// The elements in the array are in order.
String[] array = (String[])set.toArray(new String[set.size()]);
Sorting an Arrayint[] intArray = new int[] {4, 1, 3, -23};
Arrays.sort(intArray);
// [-23, 1, 3, 4]
String[] strArray = new String[] {“z”, “a”, “C”};
Arrays.sort(strArray);
// [C, a, z]
// Case-insensitive sort
Arrays.sort(strArray, String.CASE_INSENSITIVE_ORDER);
// [a, C, z]
// Reverse-order sort
Arrays.sort(strArray, Collections.reverseOrder());
// [z, a, C]
// Case-insensitive reverse-order sort
Arrays.sort(strArray, String.CASE_INSENSITIVE_ORDER);
Collections.reverse(Arrays.asList(strArray));
// [z, C, a]
Finding an Element in a Sorted Array// Create an array with an ordered list of strings
String[] sortedArray = new String[]{“ant”, “bat”, “cat”, “dog”};
// Search for the word “cat”
int index = Arrays.binarySearch(sortedArray, “cat”); // 2
// Search for a non-existent element
index = Arrays.binarySearch(sortedArray, “cow”); // -4
This example also works if the element is a primitive type.
// Create an array with an ordered list of numbers
int[] sortedIntArray = new int[]{1, 2, 3, 5, 7};
// Search for 6
index = Arrays.binarySearch(sortedIntArray, 6); // -5
A negative return value indicates that the element is not in the list. However, the actual return value can be used to determine where that non-existent element should be inserted in the list if that were desired.
Finding an Element in a Sorted List// Create a list with an ordered list of strings
List sortedList = new LinkedList();
sortedList.addAll(Arrays.asList(new String[]{“ant”, “bat”, “cat”, “dog”}));
// Search for the word “cat”
int index = Collections.binarySearch(sortedList, “cat”); // 2
// Search for a non-existent element
index = Collections.binarySearch(sortedList, “cow”); // -4
A negative return value indicates that the element is not in the list. However, the actual return value can be used to determine where that non-existent element should be inserted in the list if that were desired.