Java : Collections with Examples
Collections (Java SE 19 & JDK 19) API Examples.
You will find code examples on most Collections methods.
Summary
This class consists exclusively of static methods that operate on or return collections. It contains polymorphic algorithms that operate on collections, "wrappers", which return a new collection backed by a specified collection, and a few other odds and ends.
final var list = new ArrayList<String>();
System.out.println(list); // []
Collections.addAll(list, "aaa", "bbb", "ccc");
System.out.println(list); // [aaa, bbb, ccc]
Collections.reverse(list);
System.out.println(list); // [ccc, bbb, aaa]
final var list = new ArrayList<String>();
list.add("xxx");
list.add("yyy");
System.out.println("list : " + list);
final var unmodifiableList = Collections.unmodifiableCollection(list);
try {
unmodifiableList.add("zzz");
} catch (UnsupportedOperationException e) {
System.out.println("UnsupportedOperationExceptionf!");
}
// Result
// ↓
//list : [xxx, yyy]
//UnsupportedOperationExceptionf!
Fields
static final List EMPTY_LIST
The empty list (immutable).
System.out.println(Collections.EMPTY_LIST); // []
System.out.println(Collections.EMPTY_LIST.size()); // 0
//Collections.EMPTY_LIST.add("abc"); // UnsupportedOperationException
static final Map EMPTY_MAP
The empty map (immutable).
System.out.println(Collections.EMPTY_MAP); // {}
System.out.println(Collections.EMPTY_MAP.size()); // 0
//Collections.EMPTY_MAP.put("abc", 123); // UnsupportedOperationException
static final Set EMPTY_SET
The empty set (immutable).
System.out.println(Collections.EMPTY_SET); // []
System.out.println(Collections.EMPTY_SET.size()); // 0
//Collections.EMPTY_SET.add("abc"); // UnsupportedOperationException
Methods
static <T> boolean addAll (Collection<? super T> c, T... elements)
Adds all of the specified elements to the specified collection.
final var list = new ArrayList<String>();
System.out.println(list); // []
System.out.println(Collections.addAll(list, "a", "b", "c")); // true
System.out.println(list); // [a, b, c]
final String[] array = {"X", "Y", "Z"};
System.out.println(Collections.addAll(list, array)); // true
System.out.println(list); // [a, b, c, X, Y, Z]
final var set = new HashSet<String>();
set.add("a");
set.add("b");
System.out.println(set); // [a, b]
System.out.println(Collections.addAll(set, "a")); // false
System.out.println(set); // [a, b]
System.out.println(Collections.addAll(set, "a", "b")); // false
System.out.println(set); // [a, b]
System.out.println(Collections.addAll(set, "a", "b", "c")); // true
System.out.println(set); // [a, b, c]
static <T> Queue<T> asLifoQueue (Deque<T> deque)
Returns a view of a Deque as a Last-in-first-out (Lifo) Queue.
// FIFO
final var deque = new ArrayDeque<>();
deque.add("a");
deque.add("b");
deque.add("c");
System.out.println(deque); // [a, b, c]
System.out.println(deque.remove()); // a
System.out.println(deque); // [b, c]
System.out.println(deque.remove()); // b
System.out.println(deque); // [c]
System.out.println(deque.remove()); // c
System.out.println(deque); // []
// LIFO
final var lifoQueue = Collections.asLifoQueue(new ArrayDeque<>());
lifoQueue.add("a");
lifoQueue.add("b");
lifoQueue.add("c");
System.out.println(lifoQueue); // [c, b, a]
System.out.println(lifoQueue.remove()); // c
System.out.println(lifoQueue); // [b, a]
System.out.println(lifoQueue.remove()); // b
System.out.println(lifoQueue); // [a]
System.out.println(lifoQueue.remove()); // a
System.out.println(lifoQueue); // []
static <T> int binarySearch (List<? extends Comparable<? super T>> list, T key)
Searches the specified list for the specified object using the binary search algorithm.
// The list must be sorted into ascending order according to the natural ordering.
final var list = new ArrayList<Integer>();
Collections.addAll(list, 30, 50, 10, 40, 20);
Collections.sort(list);
System.out.println(list); // [10, 20, 30, 40, 50]
System.out.println(Collections.binarySearch(list, 10)); // 0
System.out.println(Collections.binarySearch(list, 20)); // 1
System.out.println(Collections.binarySearch(list, 30)); // 2
System.out.println(Collections.binarySearch(list, 999)); // -6
final var list = new ArrayList<String>();
Collections.addAll(list, "a", "b", "c", "a", "b", "c");
Collections.sort(list);
System.out.println(list); // [a, a, b, b, c, c]
System.out.println(Collections.binarySearch(list, "a")); // 0
System.out.println(Collections.binarySearch(list, "b")); // 2
System.out.println(Collections.binarySearch(list, "c")); // 4
System.out.println(Collections.binarySearch(list, "X")); // -1
static <T> int binarySearch (List<? extends T> list, T key, Comparator<? super T> c)
Searches the specified list for the specified object using the binary search algorithm.
final var comparator = Collections.reverseOrder();
// The list must be sorted into ascending order according to the specified comparator.
final var list = new ArrayList<Integer>();
Collections.addAll(list, 30, 50, 10, 40, 20);
list.sort(comparator);
System.out.println(list); // [50, 40, 30, 20, 10]
System.out.println(Collections.binarySearch(list, 10, comparator)); // 4
System.out.println(Collections.binarySearch(list, 20, comparator)); // 3
System.out.println(Collections.binarySearch(list, 30, comparator)); // 2
System.out.println(Collections.binarySearch(list, 999, comparator)); // -1
static <E> Collection<E> checkedCollection (Collection<E> c, Class<E> type)
Returns a dynamically typesafe view of the specified collection.
final var func = new Consumer<Collection>() {
@Override
public void accept(Collection collection) {
collection.add("aaa");
collection.add(123);
collection.add(LocalTime.of(12, 30));
}
};
// unchecked
final var uncheckedCollection = new HashSet<String>();
func.accept(uncheckedCollection);
System.out.println(uncheckedCollection); // [aaa, 123, 12:30]
// checked
final var checkedCollection = Collections.checkedCollection(uncheckedCollection, String.class);
// ClassCastException: Attempt to insert class java.lang.Integer element into collection
// with element type class java.lang.String
func.accept(checkedCollection);
static <E> List<E> checkedList (List<E> list, Class<E> type)
Returns a dynamically typesafe view of the specified list.
final var func = new Consumer<List>() {
@Override
public void accept(List list) {
list.add("aaa");
list.add(123);
list.add(LocalTime.of(12, 30));
}
};
// unchecked
final var uncheckedList = new ArrayList<String>();
func.accept(uncheckedList);
System.out.println(uncheckedList); // [aaa, 123, 12:30]
// checked
final var checkedList = Collections.checkedList(uncheckedList, String.class);
// ClassCastException: Attempt to insert class java.lang.Integer element into collection
// with element type class java.lang.String
func.accept(checkedList);
static <K, V> Map<K,V> checkedMap (Map<K,V> m, Class<K> keyType, Class<V> valueType)
Returns a dynamically typesafe view of the specified map.
final var func = new Consumer<Map>() {
@Override
public void accept(Map map) {
map.put("aaa", 123);
map.put(456, "bbb");
map.put("XXX", LocalTime.of(12, 30));
}
};
// unchecked
final var uncheckedMap = new HashMap<String, Integer>();
func.accept(uncheckedMap);
System.out.println(uncheckedMap); // {aaa=123, 456=bbb, XXX=12:30}
// checked
final var checkedMap = Collections.checkedMap(uncheckedMap, String.class, Integer.class);
// ClassCastException: Attempt to insert class java.lang.Integer key into map
// with key type class java.lang.String
func.accept(checkedMap);
static <E> Queue<E> checkedQueue (Queue<E> queue, Class<E> type)
Returns a dynamically typesafe view of the specified queue.
final var func = new Consumer<Queue>() {
@Override
public void accept(Queue queue) {
queue.add("aaa");
queue.add(123);
queue.add(LocalTime.of(12, 30));
}
};
// unchecked
final var uncheckedQueue = new ArrayDeque<String>();
func.accept(uncheckedQueue);
System.out.println(uncheckedQueue); // [aaa, 123, 12:30]
// checked
final var checkedQueue = Collections.checkedQueue(uncheckedQueue, String.class);
// ClassCastException: Attempt to insert class java.lang.Integer element into collection
// with element type class java.lang.String
func.accept(checkedQueue);
static <E> Set<E> checkedSet (Set<E> s, Class<E> type)
Returns a dynamically typesafe view of the specified set.
final var func = new Consumer<Set>() {
@Override
public void accept(Set set) {
set.add("aaa");
set.add(123);
set.add(LocalTime.of(12, 30));
}
};
// unchecked
final var uncheckedSet = new HashSet<String>();
func.accept(uncheckedSet);
System.out.println(uncheckedSet); // [aaa, 123, 12:30]
// checked
final var checkedSet = Collections.checkedSet(uncheckedSet, String.class);
// ClassCastException: Attempt to insert class java.lang.Integer element into collection
// with element type class java.lang.String
func.accept(checkedSet);
static <K, V> SortedMap<K,V> checkedSortedMap (SortedMap<K,V> m, Class<K> keyType, Class<V> valueType)
Returns a dynamically typesafe view of the specified sorted map.
final var func = new Consumer<SortedMap>() {
@Override
public void accept(SortedMap map) {
map.put("aaa", 123);
map.put("bbb", "XXX");
map.put("ccc", LocalTime.of(12, 30));
}
};
// unchecked
final var uncheckedMap = new TreeMap<String, Integer>();
func.accept(uncheckedMap);
System.out.println(uncheckedMap); // {aaa=123, bbb=XXX, ccc=12:30}
// checked
final var checkedMap = Collections.checkedSortedMap(uncheckedMap, String.class, Integer.class);
// java.lang.ClassCastException: Attempt to insert class java.lang.String value into map
// with value type class java.lang.Integer
func.accept(checkedMap);
static <E> SortedSet<E> checkedSortedSet (SortedSet<E> s, Class<E> type)
Returns a dynamically typesafe view of the specified sorted set.
final var func = new Consumer<SortedSet>() {
@Override
public void accept(SortedSet set) {
set.add("aaa");
set.add("bbb");
set.add("ccc");
}
};
// unchecked
final var uncheckedSet = new TreeSet<Integer>();
func.accept(uncheckedSet);
System.out.println(uncheckedSet); // [aaa, bbb, ccc]
// checked
final var checkedSet = Collections.checkedSortedSet(uncheckedSet, Integer.class);
// java.lang.ClassCastException: Attempt to insert class java.lang.String element into collection
// with element type class java.lang.Integer
func.accept(checkedSet);
static <T> void copy (List<? super T> dest, List<? extends T> src)
Copies all of the elements from one list into another.
final var src = new ArrayList<String>();
Collections.addAll(src, "a", "b", "c");
final var dest = new ArrayList<String>();
Collections.addAll(dest, "X", "Y", "Z");
System.out.println(src); // [a, b, c]
System.out.println(dest); // [X, Y, Z]
Collections.copy(dest, src);
System.out.println(src); // [a, b, c]
System.out.println(dest); // [a, b, c]
src.add("d");
System.out.println(src); // [a, b, c, d]
System.out.println(dest); // [a, b, c]
dest.add("XXX");
System.out.println(src); // [a, b, c, d]
System.out.println(dest); // [a, b, c, XXX]
final var src = new ArrayList<String>();
Collections.addAll(src, "a", "b", "c");
final var dest = new ArrayList<>(Collections.nCopies(5, "Z"));
System.out.println(src); // [a, b, c]
System.out.println(dest); // [Z, Z, Z, Z, Z]
Collections.copy(dest, src);
System.out.println(src); // [a, b, c]
System.out.println(dest); // [a, b, c, Z, Z]
final var src = new ArrayList<String>();
Collections.addAll(src, "a", "b", "c");
final var dest = new ArrayList<String>();
System.out.println(src); // [a, b, c]
System.out.println(dest); // []
//Collections.copy(dest, src); // IndexOutOfBoundsException: Source does not fit in dest
static boolean disjoint (Collection<?> c1, Collection<?> c2)
Returns true if the two specified collections have no elements in common.
final var c = List.of("a", "b", "c");
System.out.println(c); // [a, b, c]
System.out.println(Collections.disjoint(c, List.of("a"))); // false
System.out.println(Collections.disjoint(c, List.of("b"))); // false
System.out.println(Collections.disjoint(c, List.of("c"))); // false
System.out.println(Collections.disjoint(c, List.of("X"))); // true
System.out.println(Collections.disjoint(c, List.of("a", "b"))); // false
System.out.println(Collections.disjoint(c, List.of("b", "c"))); // false
System.out.println(Collections.disjoint(c, List.of("c", "X"))); // false
System.out.println(Collections.disjoint(c, List.of("X", "Y"))); // true
System.out.println(Collections.disjoint(c, List.of("a", "b", "X"))); // false
System.out.println(Collections.disjoint(c, List.of("a", "X", "Y"))); // false
System.out.println(Collections.disjoint(c, List.of("X", "Y", "Z"))); // true
static <T> Enumeration<T> emptyEnumeration ()
Returns an enumeration that has no elements.
final var enumeration = Collections.<DayOfWeek>emptyEnumeration();
System.out.println(enumeration.hasMoreElements()); // false
//enumeration.nextElement(); // NoSuchElementException
static <T> Iterator<T> emptyIterator ()
Returns an iterator that has no elements.
final var iterator = Collections.<String>emptyIterator();
System.out.println(iterator.hasNext()); // false
//iterator.next(); // NoSuchElementException
static final <T> List<T> emptyList ()
Returns an empty list (immutable).
final var list = Collections.<String>emptyList();
System.out.println(list); // []
System.out.println(list.isEmpty()); // true
//list.add("a"); // UnsupportedOperationException
static <T> ListIterator<T> emptyListIterator ()
Returns a list iterator that has no elements.
final var iterator = Collections.<String>emptyListIterator();
System.out.println(iterator.hasNext()); // false
System.out.println(iterator.nextIndex()); // 0
System.out.println(iterator.previousIndex()); // -1
//iterator.next(); // NoSuchElementException
static final <K, V> Map<K,V> emptyMap ()
Returns an empty map (immutable).
final var map = Collections.<String, Integer>emptyMap();
System.out.println(map); // {}
System.out.println(map.isEmpty()); // true
//map.put("a", 123); // UnsupportedOperationException
static final <T> Set<T> emptySet ()
Returns an empty set (immutable).
final var set = Collections.<String>emptySet();
System.out.println(set); // []
System.out.println(set.isEmpty()); // true
//set.add("a"); // UnsupportedOperationException
static final <K, V> SortedMap<K,V> emptySortedMap ()
Returns an empty sorted map (immutable).
final var map = Collections.<String, Integer>emptySortedMap();
System.out.println(map); // {}
System.out.println(map.isEmpty()); // true
//map.put("a", 123); // UnsupportedOperationException
static <E> SortedSet<E> emptySortedSet ()
Returns an empty sorted set (immutable).
final var set = Collections.<String>emptySortedSet();
System.out.println(set); // []
System.out.println(set.isEmpty()); // true
//set.add("a"); // UnsupportedOperationException
static <T> Enumeration<T> enumeration (Collection<T> c)
Returns an enumeration over the specified collection.
final var c = List.of(DayOfWeek.SUNDAY, DayOfWeek.MONDAY, DayOfWeek.TUESDAY);
final var enumeration = Collections.enumeration(c);
enumeration.asIterator().forEachRemaining(System.out::println);
// Result
// ↓
//SUNDAY
//MONDAY
//TUESDAY
static <T> void fill (List<? super T> list, T obj)
Replaces all of the elements of the specified list with the specified element.
final var list = new ArrayList<String>();
list.add("a");
list.add("b");
list.add("c");
System.out.println(list); // [a, b, c]
Collections.fill(list, "Z");
System.out.println(list); // [Z, Z, Z]
static int frequency (Collection<?> c, Object o)
Returns the number of elements in the specified collection equal to the specified object.
final var list = List.of("a", "a", "a", "b", "b", "c");
System.out.println(list); // [a, a, a, b, b, c]
System.out.println(Collections.frequency(list, "a")); // 3
System.out.println(Collections.frequency(list, "b")); // 2
System.out.println(Collections.frequency(list, "c")); // 1
System.out.println(Collections.frequency(list, "X")); // 0
static int indexOfSubList (List<?> source, List<?> target)
Returns the starting position of the first occurrence of the specified target list within the specified source list, or -1 if there is no such occurrence.
final var source = List.of("a", "b", "c", "d", "e", "f");
System.out.println(source); // [a, b, c, d, e, f]
System.out.println(Collections.indexOfSubList(source, List.of("a"))); // 0
System.out.println(Collections.indexOfSubList(source, List.of("b"))); // 1
System.out.println(Collections.indexOfSubList(source, List.of("c"))); // 2
System.out.println(Collections.indexOfSubList(source, List.of("d"))); // 3
System.out.println(Collections.indexOfSubList(source, List.of("e"))); // 4
System.out.println(Collections.indexOfSubList(source, List.of("f"))); // 5
System.out.println(Collections.indexOfSubList(source, List.of("g"))); // -1
System.out.println(Collections.indexOfSubList(source, List.of("a", "b"))); // 0
System.out.println(Collections.indexOfSubList(source, List.of("b", "c", "d"))); // 1
System.out.println(Collections.indexOfSubList(source, List.of("c", "d", "e", "f"))); // 2
System.out.println(Collections.indexOfSubList(source, List.of("d", "e", "f", "g"))); // -1
final var source = List.of("a", "b", "c", "a", "b", "c");
System.out.println(source); // [a, b, c, a, b, c]
System.out.println(Collections.indexOfSubList(source, List.of("a"))); // 0
System.out.println(Collections.indexOfSubList(source, List.of("b"))); // 1
System.out.println(Collections.indexOfSubList(source, List.of("c"))); // 2
System.out.println(Collections.indexOfSubList(source, List.of("a", "b"))); // 0
System.out.println(Collections.indexOfSubList(source, List.of("a", "b", "c"))); // 0
System.out.println(Collections.indexOfSubList(source, List.of("b", "c"))); // 1
System.out.println(Collections.indexOfSubList(source, List.of("b", "c", "a"))); // 1
System.out.println(Collections.indexOfSubList(source, List.of("c", "a"))); // 2
System.out.println(Collections.indexOfSubList(source, List.of("c", "a", "b"))); // 2
static int lastIndexOfSubList (List<?> source, List<?> target)
Returns the starting position of the last occurrence of the specified target list within the specified source list, or -1 if there is no such occurrence.
final var source = List.of("a", "b", "c", "d", "e", "f");
System.out.println(source); // [a, b, c, d, e, f]
System.out.println(Collections.lastIndexOfSubList(source, List.of("a"))); // 0
System.out.println(Collections.lastIndexOfSubList(source, List.of("b"))); // 1
System.out.println(Collections.lastIndexOfSubList(source, List.of("c"))); // 2
System.out.println(Collections.lastIndexOfSubList(source, List.of("d"))); // 3
System.out.println(Collections.lastIndexOfSubList(source, List.of("e"))); // 4
System.out.println(Collections.lastIndexOfSubList(source, List.of("f"))); // 5
System.out.println(Collections.lastIndexOfSubList(source, List.of("g"))); // -1
System.out.println(Collections.lastIndexOfSubList(source, List.of("a", "b"))); // 0
System.out.println(Collections.lastIndexOfSubList(source, List.of("b", "c", "d"))); // 1
System.out.println(Collections.lastIndexOfSubList(source, List.of("c", "d", "e", "f"))); // 2
System.out.println(Collections.lastIndexOfSubList(source, List.of("d", "e", "f", "g"))); // -1
final var source = List.of("a", "b", "c", "a", "b", "c");
System.out.println(source); // [a, b, c, a, b, c]
System.out.println(Collections.lastIndexOfSubList(source, List.of("a"))); // 3
System.out.println(Collections.lastIndexOfSubList(source, List.of("b"))); // 4
System.out.println(Collections.lastIndexOfSubList(source, List.of("c"))); // 5
System.out.println(Collections.lastIndexOfSubList(source, List.of("a", "b"))); // 3
System.out.println(Collections.lastIndexOfSubList(source, List.of("a", "b", "c"))); // 3
System.out.println(Collections.lastIndexOfSubList(source, List.of("a", "b", "c", "a"))); // 0
System.out.println(Collections.lastIndexOfSubList(source, List.of("b", "c"))); // 4
System.out.println(Collections.lastIndexOfSubList(source, List.of("b", "c", "a"))); // 1
System.out.println(Collections.lastIndexOfSubList(source, List.of("b", "c", "a", "b"))); // 1
static <T> ArrayList<T> list (Enumeration<T> e)
Returns an array list containing the elements returned by the specified enumeration in the order they are returned by the enumeration.
final var vector = new Vector<DayOfWeek>();
Collections.addAll(vector, DayOfWeek.SUNDAY, DayOfWeek.MONDAY, DayOfWeek.TUESDAY);
System.out.println(vector); // [SUNDAY, MONDAY, TUESDAY]
final var list = Collections.list(vector.elements());
System.out.println(list); // [SUNDAY, MONDAY, TUESDAY]
static <T extends Object & Comparable<? super T>> T max (Collection<? extends T> coll)
Returns the maximum element of the given collection, according to the natural ordering of its elements.
final var list = List.of(1, 5, 999, -1000, 200);
System.out.println(Collections.max(list)); // 999
final var list = List.of("aaa", "ccc", "bbb");
System.out.println(Collections.max(list)); // ccc
final var set = Set.of("a", "x", "b", "y", "z", "c");
System.out.println(Collections.max(set)); // z
static <T> T max (Collection<? extends T> coll, Comparator<? super T> comp)
Returns the maximum element of the given collection, according to the order induced by the specified comparator.
final var list = List.of(1, 5, 999, -1000, 200);
System.out.println(Collections.max(list)); // 999
System.out.println(Collections.max(list, Comparator.comparingInt(Math::abs))); // -1000
final var set = Set.of("aaa", "bbb", "XXX", "YYY");
System.out.println(Collections.max(set)); // bbb
System.out.println(Collections.max(set, String.CASE_INSENSITIVE_ORDER)); // YYY
final var list = List.of("a", "x", "b", "y", "z", "c");
System.out.println(Collections.max(list)); // z
System.out.println(Collections.max(list, Comparator.reverseOrder())); // a
static <T extends Object & Comparable<? super T>> T min (Collection<? extends T> coll)
Returns the minimum element of the given collection, according to the natural ordering of its elements.
final var list = List.of(1, 5, 999, -1000, 200);
System.out.println(Collections.min(list)); // -1000
final var list = List.of("aaa", "ccc", "bbb");
System.out.println(Collections.min(list)); // aaa
final var set = Set.of("a", "x", "b", "y", "z", "c");
System.out.println(Collections.min(set)); // a
static <T> T min (Collection<? extends T> coll, Comparator<? super T> comp)
Returns the minimum element of the given collection, according to the order induced by the specified comparator.
final var list = List.of(1, 5, 999, -1000, 200);
System.out.println(Collections.min(list)); // -1000
System.out.println(Collections.min(list, Comparator.comparingInt(Math::abs))); // 1
final var set = Set.of("aaa", "bbb", "XXX", "YYY");
System.out.println(Collections.min(set)); // XXX
System.out.println(Collections.min(set, String.CASE_INSENSITIVE_ORDER)); // aaa
final var list = List.of("a", "x", "b", "y", "z", "c");
System.out.println(Collections.min(list)); // a
System.out.println(Collections.min(list, Comparator.reverseOrder())); // z
static <T> List<T> nCopies (int n, T o)
Returns an immutable list consisting of n copies of the specified object.
final var list1 = Collections.nCopies(0, "abc");
System.out.println(list1); // []
final var list2 = Collections.nCopies(1, "abc");
System.out.println(list2); // [abc]
final var list3 = Collections.nCopies(2, "abc");
System.out.println(list3); // [abc, abc]
final var list = Collections.nCopies(10, "X");
System.out.println(list); // [X, X, X, X, X, X, X, X, X, X]
//list.add("Y"); // UnsupportedOperationException
static <E> Set<E> newSetFromMap (Map<E,Boolean> map)
Returns a set backed by the specified map.
final var map = new WeakHashMap<String, Boolean>();
final var set = Collections.newSetFromMap(map);
System.out.println(map); // {}
System.out.println(set); // []
set.add("a");
set.add("b");
set.add("c");
System.out.println(map); // {a=true, c=true, b=true}
System.out.println(set); // [a, c, b]
static <T> boolean replaceAll (List<T> list, T oldVal, T newVal)
Replaces all occurrences of one specified value in a list with another.
final var list = new ArrayList<>();
Collections.addAll(list, "a", "b", "c");
System.out.println(list); // [a, b, c]
System.out.println(Collections.replaceAll(list, "a", "A")); // true
System.out.println(list); // [A, b, c]
System.out.println(Collections.replaceAll(list, "b", "B")); // true
System.out.println(list); // [A, B, c]
System.out.println(Collections.replaceAll(list, "x", "X")); // false
System.out.println(list); // [A, B, c]
System.out.println(Collections.replaceAll(list, "A", "A")); // true
System.out.println(list); // [A, B, c]
final var list = new ArrayList<>();
Collections.addAll(list, "a", "a", "a", "b", "b", "b");
System.out.println(list); // [a, a, a, b, b, b]
System.out.println(Collections.replaceAll(list, "a", "A")); // true
System.out.println(list); // [A, A, A, b, b, b]
System.out.println(Collections.replaceAll(list, "b", "B")); // true
System.out.println(list); // [A, A, A, B, B, B]
System.out.println(Collections.replaceAll(list, "x", "X")); // false
System.out.println(list); // [A, A, A, B, B, B]
static void reverse (List<?> list)
Reverses the order of the elements in the specified list.
final var list = new ArrayList<>();
Collections.addAll(list, 1, 2, 3, 4, 5);
System.out.println(list); // [1, 2, 3, 4, 5]
Collections.reverse(list);
System.out.println(list); // [5, 4, 3, 2, 1]
final var list = new ArrayList<>();
Collections.addAll(list, "a", "b", "c", "A", "B", "C");
System.out.println(list); // [a, b, c, A, B, C]
Collections.reverse(list);
System.out.println(list); // [C, B, A, c, b, a]
static <T> Comparator<T> reverseOrder ()
Returns a comparator that imposes the reverse of the natural ordering on a collection of objects that implement the Comparable interface.
final var list = new ArrayList<Integer>();
Collections.addAll(list, 1, 5, 14, 2, -10);
System.out.println(list); // [1, 5, 14, 2, -10]
Collections.sort(list);
System.out.println(list); // [-10, 1, 2, 5, 14]
list.sort(Collections.reverseOrder());
System.out.println(list); // [14, 5, 2, 1, -10]
final var list = new ArrayList<String>();
Collections.addAll(list, "a", "A", "x", "X", "b", "B");
System.out.println(list); // [a, A, x, X, b, B]
Collections.sort(list);
System.out.println(list); // [A, B, X, a, b, x]
list.sort(Collections.reverseOrder());
System.out.println(list); // [x, b, a, X, B, A]
static <T> Comparator<T> reverseOrder (Comparator<T> cmp)
Returns a comparator that imposes the reverse ordering of the specified comparator.
final var list = new ArrayList<Integer>();
Collections.addAll(list, 1, 5, 14, 2, -10);
System.out.println(list); // [1, 5, 14, 2, -10]
list.sort(Comparator.comparingInt(Math::abs));
System.out.println(list); // [1, 2, 5, -10, 14]
list.sort(Collections.reverseOrder(Comparator.comparingInt(Math::abs)));
System.out.println(list); // [14, -10, 5, 2, 1]
final var list = new ArrayList<String>();
Collections.addAll(list, "a", "A", "x", "X", "b", "B");
System.out.println(list); // [a, A, x, X, b, B]
list.sort(String.CASE_INSENSITIVE_ORDER);
System.out.println(list); // [a, A, b, B, x, X]
list.sort(Collections.reverseOrder(String.CASE_INSENSITIVE_ORDER));
System.out.println(list); // [x, X, b, B, a, A]
static void rotate (List<?> list, int distance)
Rotates the elements in the specified list by the specified distance.
final var src = List.of("X", "a", "b", "c");
System.out.println(src); // [X, a, b, c]
{
final var list = new ArrayList<>(src);
Collections.rotate(list, -1);
System.out.println(list); // [a, b, c, X]
}
{
final var list = new ArrayList<>(src);
Collections.rotate(list, 0);
System.out.println(list); // [X, a, b, c]
}
{
final var list = new ArrayList<>(src);
Collections.rotate(list, 1);
System.out.println(list); // [c, X, a, b]
}
{
final var list = new ArrayList<>(src);
Collections.rotate(list, 2);
System.out.println(list); // [b, c, X, a]
}
{
final var list = new ArrayList<>(src);
Collections.rotate(list, 3);
System.out.println(list); // [a, b, c, X]
}
{
final var list = new ArrayList<>(src);
Collections.rotate(list, 4);
System.out.println(list); // [X, a, b, c]
}
{
final var list = new ArrayList<>(src);
Collections.rotate(list, 5);
System.out.println(list); // [c, X, a, b]
}
static void shuffle (List<?> list)
Randomly permutes the specified list using a default source of randomness.
final var list = new ArrayList<String>();
Collections.addAll(list, "a", "b", "c", "d");
System.out.println(list); // [a, b, c, d]
Collections.shuffle(list);
System.out.println(list); // [c, b, a, d]
Collections.shuffle(list);
System.out.println(list); // [d, a, b, c]
Collections.shuffle(list);
System.out.println(list); // [c, a, d, b]
static void shuffle (List<?> list, Random rnd)
Randomly permute the specified list using the specified source of randomness.
final var src = List.of("a", "b", "c", "d");
System.out.println(src); // [a, b, c, d]
// An example with using the same seed.
final var seed = 0;
for (int i = 0; i < 3; i++) {
final var rnd = new Random(seed);
final var list = new ArrayList<>(src);
System.out.println("-------");
Collections.shuffle(list, rnd);
System.out.println(list);
Collections.shuffle(list, rnd);
System.out.println(list);
}
// Result
// ↓
//-------
//[d, a, b, c]
//[a, d, c, b]
//-------
//[d, a, b, c]
//[a, d, c, b]
//-------
//[d, a, b, c]
//[a, d, c, b]
static <T> Set<T> singleton (T o)
Returns an immutable set containing only the specified object.
final var set = Collections.singleton("aaa");
System.out.println(set); // [aaa]
System.out.println(set.size()); // 1
final var set = Collections.singleton(123);
System.out.println(set); // [123]
System.out.println(set.size()); // 1
//set.add(456); // UnsupportedOperationException
static <T> List<T> singletonList (T o)
Returns an immutable list containing only the specified object.
final var list = Collections.singletonList("aaa");
System.out.println(list); // [aaa]
System.out.println(list.size()); // 1
final var list = Collections.singletonList(123);
System.out.println(list); // [123]
System.out.println(list.size()); // 1
//list.add(456); // UnsupportedOperationException
static <K, V> Map<K,V> singletonMap (K key, V value)
Returns an immutable map, mapping only the specified key to the specified value.
final var map = Collections.singletonMap("a", 123);
System.out.println(map); // {a=123}
System.out.println(map.size()); // 1
final var map = Collections.singletonMap(456, "b");
System.out.println(map); // {456=b}
System.out.println(map.size()); // 1
//map.put(999, "xxx"); // UnsupportedOperationException
static <T extends Comparable<? super T>> void sort (List<T> list)
Sorts the specified list into ascending order, according to the natural ordering of its elements.
final var list = new ArrayList<Integer>();
Collections.addAll(list, 1, 5, 14, 2, -10);
System.out.println(list); // [1, 5, 14, 2, -10]
Collections.sort(list);
System.out.println(list); // [-10, 1, 2, 5, 14]
final var list = new ArrayList<String>();
Collections.addAll(list, "a", "x", "y", "z", "b", "c");
System.out.println(list); // [a, x, y, z, b, c]
Collections.sort(list);
System.out.println(list); // [a, b, c, x, y, z]
static <T> void sort (List<T> list, Comparator<? super T> c)
Sorts the specified list according to the order induced by the specified comparator.
final var list = new ArrayList<Integer>();
Collections.addAll(list, 1, 5, 14, 2, -10);
System.out.println(list); // [1, 5, 14, 2, -10]
Collections.sort(list);
System.out.println(list); // [-10, 1, 2, 5, 14]
Collections.sort(list, Collections.reverseOrder());
System.out.println(list); // [14, 5, 2, 1, -10]
final var list = new ArrayList<String>();
Collections.addAll(list, "a", "x", "y", "z", "b", "c");
System.out.println(list); // [a, x, y, z, b, c]
Collections.sort(list);
System.out.println(list); // [a, b, c, x, y, z]
Collections.sort(list, Collections.reverseOrder());
System.out.println(list); // [z, y, x, c, b, a]
static void swap (List<?> list, int i, int j)
Swaps the elements at the specified positions in the specified list.
final var src = List.of("X", "a", "b", "c");
System.out.println(src); // [X, a, b, c]
final var list1 = new ArrayList<>(src);
//Collections.swap(list1, 0, -1); // IndexOutOfBoundsException
final var list2 = new ArrayList<>(src);
Collections.swap(list2, 0, 0);
System.out.println(list2); // [X, a, b, c]
final var list3 = new ArrayList<>(src);
Collections.swap(list3, 0, 1);
System.out.println(list3); // [a, X, b, c]
final var list4 = new ArrayList<>(src);
Collections.swap(list4, 0, 2);
System.out.println(list4); // [b, a, X, c]
final var list5 = new ArrayList<>(src);
Collections.swap(list5, 0, 3);
System.out.println(list5); // [c, a, b, X]
final var list6 = new ArrayList<>(src);
//Collections.swap(list6, 0, 4); // IndexOutOfBoundsException
final var src = List.of("a", "b", "X", "c");
System.out.println(src); // [a, b, X, c]
final var list1 = new ArrayList<>(src);
//Collections.swap(list1, -1, 2); // IndexOutOfBoundsException
final var list2 = new ArrayList<>(src);
Collections.swap(list2, 0, 2);
System.out.println(list2); // [X, b, a, c]
final var list3 = new ArrayList<>(src);
Collections.swap(list3, 1, 2);
System.out.println(list3); // [a, X, b, c]
final var list4 = new ArrayList<>(src);
Collections.swap(list4, 2, 2);
System.out.println(list4); // [a, b, X, c]
final var list5 = new ArrayList<>(src);
Collections.swap(list5, 3, 2);
System.out.println(list5); // [a, b, c, X]
final var list6 = new ArrayList<>(src);
//Collections.swap(list6, 4, 2); // IndexOutOfBoundsException
static <T> Collection<T> synchronizedCollection (Collection<T> c)
Returns a synchronized (thread-safe) collection backed by the specified collection.
final var synchronizedCollection = Collections.synchronizedCollection(new ArrayList<String>());
final var executor = Executors.newWorkStealingPool(10);
try {
IntStream.range(0, 100).forEach(i -> {
executor.submit(() -> {
synchronizedCollection.add("a");
});
});
} finally {
executor.shutdown();
final var ret = executor.awaitTermination(10, TimeUnit.SECONDS);
System.out.println(ret); // true
}
System.out.println(synchronizedCollection.size()); // 100
static <T> List<T> synchronizedList (List<T> list)
Returns a synchronized (thread-safe) list backed by the specified list.
final var synchronizedList = Collections.synchronizedList(new ArrayList<String>());
final var executor = Executors.newWorkStealingPool(10);
try {
IntStream.range(0, 100).forEach(i -> {
executor.submit(() -> {
synchronizedList.add("a");
});
});
} finally {
executor.shutdown();
final var ret = executor.awaitTermination(10, TimeUnit.SECONDS);
System.out.println(ret); // true
}
System.out.println(synchronizedList.size()); // 100
static <K, V> Map<K,V> synchronizedMap (Map<K,V> m)
Returns a synchronized (thread-safe) map backed by the specified map.
final var synchronizedMap = Collections.synchronizedMap(new HashMap<Integer, String>());
final var executor = Executors.newWorkStealingPool(10);
try {
IntStream.range(0, 100).forEach(i -> {
executor.submit(() -> {
synchronizedMap.put(i, "a");
});
});
} finally {
executor.shutdown();
final var ret = executor.awaitTermination(10, TimeUnit.SECONDS);
System.out.println(ret); // true
}
System.out.println(synchronizedMap.size()); // 100
static <T> Set<T> synchronizedSet (Set<T> s)
Returns a synchronized (thread-safe) set backed by the specified set.
final var synchronizedSet = Collections.synchronizedSet(new HashSet<Integer>());
final var executor = Executors.newWorkStealingPool(10);
try {
IntStream.range(0, 100).forEach(i -> {
executor.submit(() -> {
synchronizedSet.add(i);
});
});
} finally {
executor.shutdown();
final var ret = executor.awaitTermination(10, TimeUnit.SECONDS);
System.out.println(ret); // true
}
System.out.println(synchronizedSet.size()); // 100
static <K, V> SortedMap<K,V> synchronizedSortedMap (SortedMap<K,V> m)
Returns a synchronized (thread-safe) sorted map backed by the specified sorted map.
final var synchronizedMap = Collections.synchronizedSortedMap(new TreeMap<Integer, String>());
final var executor = Executors.newWorkStealingPool(10);
try {
IntStream.range(0, 100).forEach(i -> {
executor.submit(() -> {
synchronizedMap.put(i, "a");
});
});
} finally {
executor.shutdown();
final var ret = executor.awaitTermination(10, TimeUnit.SECONDS);
System.out.println(ret); // true
}
System.out.println(synchronizedMap.size()); // 100
static <T> SortedSet<T> synchronizedSortedSet (SortedSet<T> s)
Returns a synchronized (thread-safe) sorted set backed by the specified sorted set.
final var synchronizedSet = Collections.synchronizedSortedSet(new TreeSet<Integer>());
final var executor = Executors.newWorkStealingPool(10);
try {
IntStream.range(0, 100).forEach(i -> {
executor.submit(() -> {
synchronizedSet.add(i);
});
});
} finally {
executor.shutdown();
final var ret = executor.awaitTermination(10, TimeUnit.SECONDS);
System.out.println(ret); // true
}
System.out.println(synchronizedSet.size()); // 100
static <T> Collection<T> unmodifiableCollection (Collection<? extends T> c)
Returns an unmodifiable view of the specified collection.
final var list = new ArrayList<String>();
list.add("a");
list.add("b");
list.add("c");
System.out.println(list); // [a, b, c]
final var unmodifiableCollection = Collections.unmodifiableCollection(list);
System.out.println(unmodifiableCollection); // [a, b, c]
System.out.println(unmodifiableCollection.contains("b")); // true
System.out.println(unmodifiableCollection.contains("X")); // false
//unmodifiableCollection.add("d"); // UnsupportedOperationException
static <T> List<T> unmodifiableList (List<? extends T> list)
Returns an unmodifiable view of the specified list.
final var list = new ArrayList<String>();
list.add("a");
list.add("b");
list.add("c");
System.out.println(list); // [a, b, c]
final var unmodifiableList = Collections.unmodifiableList(list);
System.out.println(unmodifiableList); // [a, b, c]
System.out.println(unmodifiableList.get(0)); // a
System.out.println(unmodifiableList.get(1)); // b
//unmodifiableList.add("d"); // UnsupportedOperationException
static <K, V> Map<K,V> unmodifiableMap (Map<? extends K,? extends V> m)
Returns an unmodifiable view of the specified map.
final var map = new HashMap<String, Integer>();
map.put("a", 100);
map.put("b", 200);
map.put("c", 300);
System.out.println(map); // {a=100, b=200, c=300}
final var unmodifiableMap = Collections.unmodifiableMap(map);
System.out.println(unmodifiableMap); // {a=100, b=200, c=300}
System.out.println(unmodifiableMap.get("a")); // 100
System.out.println(unmodifiableMap.get("b")); // 200
//unmodifiableMap.put("d", 400); // UnsupportedOperationException
static <T> Set<T> unmodifiableSet (Set<? extends T> s)
Returns an unmodifiable view of the specified set.
final var set = new HashSet<String>();
set.add("a");
set.add("b");
set.add("c");
System.out.println(set); // [a, b, c]
final var unmodifiableSet = Collections.unmodifiableSet(set);
System.out.println(unmodifiableSet); // [a, b, c]
System.out.println(unmodifiableSet.contains("b")); // true
System.out.println(unmodifiableSet.contains("X")); // false
//unmodifiableSet.add("d"); // UnsupportedOperationException
static <K, V> SortedMap<K,V> unmodifiableSortedMap (SortedMap<K,? extends V> m)
Returns an unmodifiable view of the specified sorted map.
final var map = new TreeMap<String, Integer>();
map.put("a", 100);
map.put("b", 200);
map.put("c", 300);
System.out.println(map); // {a=100, b=200, c=300}
final var unmodifiableMap = Collections.unmodifiableSortedMap(map);
System.out.println(unmodifiableMap); // {a=100, b=200, c=300}
System.out.println(unmodifiableMap.get("a")); // 100
System.out.println(unmodifiableMap.get("b")); // 200
//unmodifiableMap.put("d", 400); // UnsupportedOperationException
static <T> SortedSet<T> unmodifiableSortedSet (SortedSet<T> s)
Returns an unmodifiable view of the specified sorted set.
final var set = new TreeSet<String>();
set.add("a");
set.add("b");
set.add("c");
System.out.println(set); // [a, b, c]
final var unmodifiableSet = Collections.unmodifiableSortedSet(set);
System.out.println(unmodifiableSet); // [a, b, c]
System.out.println(unmodifiableSet.contains("b")); // true
System.out.println(unmodifiableSet.contains("X")); // false
//unmodifiableSet.add("d"); // UnsupportedOperationException
Related posts
- API Examples