- To remove all
null
's from a collection:
c.removeAll(Collections.singleton(null));
-
To remove all elements that map to a specified value from a
Map
:If you have a
Map
that maps people to their occupation and you want to eliminate all the lawyers:
map.values().removeAll(Collections.singleton(LAWYER));
- To add multiple values to already initialized
List
:
list.addAll(Arrays.asList(a, b, c, d, e, f, g));
- To add multiple values to a not yet initialized
List
:
List<E> list = new ArrayList<E>(Arrays.asList(a, b, c, d, e, f, g));
- To modify a
List
during iteration withListIterator
:
Unlike ListIterator
, Iterator
allows you to delete elements, but not to replace an existing element or to add a new one.
List<String> list = Arrays.asList(" a ", " b ", " c ");
ListIterator<String> it = list.listIterator();
while (it.hasNext()) {
it.set(it.next().trim());
}
- To iterate over the keys in a
Map
:
for (K key: map.keySet()){
System.out.println(key);
}
- To iterate over the keys in a
Map
with anIterator
:
Iterator<K> it = map.keySet().iterator();
while (it.hasNext()) {
System.out.println(it.next());
}
- To iterate over key-value pairs in a
Map
:
for (Map.Entry<K, V> el: map.entrySet()) {
System.out.println(el.getKey() + ": " + el.getValue());
}
- To sort
Map
by keys usingTreeMap
:
TreeMap
is slower than HashMap
because it runs sorting operation with each insertion, update and removal in O(log n).
Map<K,V> sortedMap = new TreeMap<K,V>(map);
- To sort
Map
by keys:
LinkedHashMap
will keep the keys in the order they are inserted.
List<K> keys = new ArrayList<K>(map.keySet());
Collections.sort(keys);
Map<K,V> sortedMap = new LinkedHashMap<K,V>();
for(K key: keys){
sortedMap.put(key, map.get(key));
}
- To sort
Map
by values:
List<Map.Entry<K,V>> entries = new LinkedList<Map.Entry<K,V>>(map.entrySet());
Collections.sort(entries, new Comparator<Map.Entry<K,V>>() {
@Override
public int compare(Entry<K, V> o1, Entry<K, V> o2) {
return o1.getValue().compareTo(o2.getValue());
}
});
Map<K,V> sortedMap = new LinkedHashMap<K,V>();
for(Map.Entry<K,V> entry: entries){
sortedMap.put(entry.getKey(), entry.getValue());
}
SortedSet
endpoint operations:
To go one element backward from a specified interior object obj
in a sorted set:
Object predecessor = sortedSet.headSet(obj).last();
- Reverse Order Comparator:
public class ReverseOrderComparator {
public static final Comparator<Integer> REVERSE_ORDER = new Comparator<Integer>() {
public int compare(Integer e1, Integer e2) {
return (e1 < e2 ? 1 : (e1 == e2 ? 0 : -1));
}
};
public static void main(String[] args) {
Integer[] array = { Integer.MIN_VALUE, Integer.MAX_VALUE, 0 };
Arrays.sort(array, REVERSE_ORDER);
System.out.println(Arrays.toString(array));
}
}