A review note of the Collections Framework. Since I reviewed mainly the part added in the Java 8 stream, the content is quite biased.
environment
reference
The sample code in this article uses the following class, enum.
Class used in the sample code
public class Employee {
private Long id;
private String name;
public Employee(Long id, String name) {
this.id = id;
this.name = name;
}
// getter/setter omitted
@Override
public String toString() {
return "Employee{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
}
Enum used in sample code
public enum DeepPurple {
IanGillan("vocal"),
SteveMorse("guitar"),
RogerGlover("base"),
IanPaice("drums"),
DonAirey("keyboard");
private String part;
DeepPurple(String part) {
this.part = part;
}
public String getPart() {
return part;
}
}
A utility class that manipulates collections.
Add any number of elements passed in the second argument to the collection passed in the first argument.
addAll
@SafeVarargs
public static <T> boolean addAll(Collection<? super T> c, T... elements)
Add an element to the List
Example
List<String> lists = new ArrayList<>();
lists.add("rubytomato");
Collections.addAll(lists,
"garnetpepper",
"spinelginger",
"rubellitebeets"
);
System.out.println(lists);
// → [rubytomato, garnetpepper, spinelginger, rubellitebeets]
Add an element to Set
Example
Set<String> sets = new HashSet<>();
sets.add("rubytomato");
Collections.addAll(sets,
"garnetpepper",
"spinelginger",
"rubellitebeets"
);
System.out.println(sets);
// → [rubytomato, spinelginger, rubellitebeet, garnetpepper]
The List passed in the first argument is sorted by the comparator passed in the second argument.
sort
public static <T> void sort(List<T> list, Comparator<? super T> c)
Sort Integer
Example
List<Integer> lists = Arrays.asList(5, 3, 1, 4, 2);
System.out.println(lists);
// → [5, 3, 1, 4, 2]
// Integer.Sort by the result of compareTo
Collections.sort(lists, Integer::compareTo);
System.out.println(lists);
// → [1, 2, 3, 4, 5]
Sort String
Example
List<String> lists = Arrays.asList("bbbb", "ddd", "aaaaa", "c", "ee");
System.out.println(lists);
// → [bbbb, ddd, aaaaa, c, ee]
//Sort by natural order of strings
Collections.sort(lists, Comparator.naturalOrder());
System.out.println(lists);
// → [aaaaa, bbbb, c, ddd, ee]
//Sort in reverse order of natural order of strings
Collections.sort(lists, Comparator.reverseOrder());
System.out.println(lists);
// → [ee, ddd, c, bbbb, aaaaa]
//Sort by string length
Collections.sort(lists, Comparator.comparing(String::length));
System.out.println(lists);
// → [c, ee, ddd, bbbb, aaaaa]
Example
Employee emp1 = new Employee(100L, "rubytomato");
Employee emp2 = new Employee(200L, "garnetpepper");
Employee emp3 = new Employee(300L, "spinelginger");
Employee emp4 = new Employee(400L, "rubellitebeets");
List<Employee> lists = Arrays.asList(emp4, emp3, emp2, emp1);
System.out.println(lists);
// → [Employee{id=400, name='rubellitebeets'}, Employee{id=300, name='spinelginger'}, Employee{id=200, name='garnetpepper'}, Employee{id=100, name='rubytomato'}]
// Employee.Sort numerically by id
Collections.sort(lists, Comparator.comparing(Employee::getId));
System.out.println(lists);
// → [Employee{id=100, name='rubytomato'}, Employee{id=200, name='garnetpepper'}, Employee{id=300, name='spinelginger'}, Employee{id=400, name='rubellitebeets'}]
List also has a sort method, so you can do the following without using Collections.
Example
lists.sort(Comparator.comparing(Employee::getId));
List
The implementation class of List is java.util.Collections.EmptyList
, and UnsupportedOperationException is thrown when the number of elements changes (add, addAll method, etc.).
emptyList
public static final <T> List<T> emptyList()
Example
List<String> lists = Collections.emptyList();
Set
The implementation class of Set is java.util.Collections.EmptySet
, and UnsupportedOperationException is thrown when the number of elements changes (add, addAll method, etc.).
emptySet
public static final <T> Set<T> emptySet()
Example
Set<String> sets = Collections.emptySet();
Map
The implementation class of Map is java.util.Collections.EmptyMap
, and UnsupportedOperationException is thrown when the number of elements changes (put, putAll method, etc.).
emptyMap
public static final <K,V> Map<K,V> emptyMap()
Example
Map<Long, String> maps = Collections.emptyMap();
List
The implementation class of List is java.util.Collections.SingletonList
, which returns a List with only the elements passed as arguments. If you change the number of elements (add, addAll, remove, clear methods, etc.) or change the elements (set, replaceAll methods, etc.), an UnsupportedOperationException will be thrown.
singletonList
public static <T> List<T> singletonList(T o)
Example
List<String> list = Collections.singletonList("rubytomato");
Set
The implementation class of Set is java.util.Collections.SingletonSet
, which returns a Set with only the elements passed as arguments. If you change the number of elements (add, remove, clear method, etc.), an UnsupportedOperationException will be thrown.
singleton
public static <T> Set<T> singleton(T o)
Example
Set<String> set = Collections.singleton("rubytomato");
Map
The implementation class of Map is java.util.Collections.SingletonMap
, which returns Map with only the key / value passed as an argument. If you change the number of elements (put, remove, clear methods, etc.) or change the elements (replace, replaceAll methods, etc.), an UnsupportedOperationException will be thrown.
singletonMap
public static <K,V> Map<K,V> singletonMap(K key, V value)
Example
Map<Long, String> map = Collections.singletonMap(100L, "rubytomato");
Collection
The implementation class is java.util.Collections.UnmodifiableCollection
, which returns an immutable collection of the Collection passed as an argument. If you change the number of elements (add, remove, clear method, etc.), an UnsupportedOperationException will be thrown.
unmodifiableCollection
public static <T> Collection<T> unmodifiableCollection(Collection<? extends T> c)
Example
List<String> lists = new ArrayList<>();
Collections.addAll(lists, "ruby", "garnet", "spinel");
Collection<String> unmodifiable = Collections.unmodifiableCollection(lists);
unmodifiable.add("rubellite");
//→ Throw UnsupportedOperationException
List
The implementation class of List is java.util.Collections.UnmodifiableRandomAccessList
, which returns an immutable collection of List passed as an argument. If you change the number of elements (add, addAll, remove, clear methods, etc.) or change the elements (set, replaceAll methods, etc.), an UnsupportedOperationException will be thrown.
unmodifiableList
public static <T> List<T> unmodifiableList(List<? extends T> list)
Example
List<String> lists = new ArrayList<>();
Collections.addAll(lists, "ruby", "garnet", "spinel");
List<String> unmodifiedLists = Collections.unmodifiableList(lists);
unmodifiedLists.add("rubellite");
//→ Throw UnsupportedOperationException
Set
The implementation class of Set is java.util.Collections.UnmodifiableSet
, which returns an immutable collection of the Set passed as an argument. If you change the number of elements (add, remove, clear method, etc.), an UnsupportedOperationException will be thrown.
unmodifiableSet
public static <T> Set<T> unmodifiableSet(Set<? extends T> s)
Example
Set<String> sets = new HashSet<>();
Collections.addAll(sets, "ruby", "garnet", "spinel");
Set<String> unmodifiedSets = Collections.unmodifiableSet(sets);
unmodifiedSets.add("rubellite");
//→ Throw UnsupportedOperationException
Map
The implementation class of Map is java.util.Collections.UnmodifiableMap
, which returns the invariant map of the Map passed as an argument. If you change the number of elements (put, remove, clear methods, etc.) or change the elements (replace, replaceAll methods, etc.), an UnsupportedOperationException will be thrown.
unmodifiableMap
public static <K,V> Map<K,V> unmodifiableMap(Map<? extends K,? extends V> m)
Example
Map<Long, String> maps = new HashMap<>();
maps.put(100L, "ruby");
maps.put(200L, "garnet");
maps.put(300L, "spinel");
Map<Long, String> unmodifiedMaps = Collections.unmodifiableMap(maps);
unmodifiedMaps.put(400L, "rubellite");
//→ Throw UnsupportedOperationException
A utility class for manipulating arrays.
The implementation class of List is java.util.Arrays.ArrayList
, which generates and returns List from the array passed as an argument. If you change the number of elements (add, remove method, etc.), an UnsupportedOperationException will be thrown.
You can change the elements (set, replaceAll method, etc.).
asList
@SafeVarargs
public static <T> List<T> asList(T... a)
Example
String[] arrays = new String[] {"rubytomato", "garnetpepper", "spinelginger"};
List<String> lists = Arrays.asList(arrays);
System.out.println(lists);
// → [rubytomato, garnetpepper, spinelginger]
Example
List<String> lists = Arrays.asList("rubytomato", "garnetpepper", "spinelginger");
System.out.println(lists);
// → [rubytomato, garnetpepper, spinelginger]
//Update elements to all uppercase
lists.replaceAll(String::toUpperCase);
System.out.println(lists);
// → [RUBYTOMATO, GARNETPEPPER, SPINELGINGER]
Introduction version Java 1.8 </ font>
Update each element of the array passed in the first argument with the operation result of the function passed in the second argument.
setAll
public static <T> void setAll(T[] array,
IntFunction<? extends T> generator)
Example
String[] arrays = new String[] {"rubytomato", "garnetpepper", "spinelginger", "rubellitebeets"};
Arrays.stream(arrays).forEach(e -> { System.out.println(e + " ID:" + System.identityHashCode(e));});
// → rubytomato ID:864237698
// → garnetpepper ID:537548559
// → spinelginger ID:380894366
// → rubellitebeets ID:237852351
Arrays.setAll(arrays, index -> {
if (index % 2 == 0) {
return arrays[index].toUpperCase();
}
return arrays[index];
});
Arrays.stream(arrays).forEach(e -> { System.out.println(e + " ID:" + System.identityHashCode(e));});
// → RUBYTOMATO ID:1221555852
// → garnetpepper ID:537548559
// → SPINELGINGER ID:1509514333
// → rubellitebeets ID:237852351
Introduction version Java 1.8 </ font>
Create a Stream from the array passed as an argument.
stream
public static <T> Stream<T> stream(T[] array)
Example
String[] arrays = new String[] {"rubytomato", "garnetpepper", "spinelginger"};
Arrays.stream(arrays).forEach(System.out::println);
// → rubytomato
// → garnetpepper
// → spinelginger
Check if the two arrays passed as arguments are equivalent (each element is equivalent in the same sequence).
equals
public static boolean equals(Object[] a, Object[] a2)
Example
String[] arrays1 = new String[] {"ruby", "garnet", "spinel", "rubellite"};
String[] arrays2 = new String[] {"ruby", "garnet", "spinel", "rubellite"};
String[] arrays3 = new String[] {"garnet", "ruby", "spinel", "rubellite"};
System.out.println(arrays1.equals(arrays2));
// → false
System.out.println(Arrays.equals(arrays1, arrays2));
// → true
//If the arrangement of elements is not the same, it will not be judged as equivalent
System.out.println(Arrays.equals(arrays1, arrays3));
// → false
Check if the two arrays passed as arguments are equivalent. For multidimensional arrays.
deepEquals
public static boolean deepEquals(Object[] a1, Object[] a2)
Example
String[][] arrays1 = new String[][] {
{"ruby", "garnet"},
{"spinel", "rubellite"}
};
String[][] arrays2 = new String[][] {
{"ruby", "garnet"},
{"spinel", "rubellite"}
};
System.out.println(Arrays.equals(arrays1, arrays2));
// → false
System.out.println(Arrays.deepEquals(arrays1, arrays2));
// → true
Returns the string representation of the array passed as an argument. If the array is null, the string "null" is returned.
toString
public static String toString(Object[] a)
Example
Employee[] employees = new Employee[] {
new Employee(100L, "rubytomato"),
new Employee(200L, "garnetpepper"),
new Employee(300L, "rubytomato"),
new Employee(400L, "rubellitebeets")
};
System.out.println(employees.toString());
// → [Lcom.example.Employee;@51521cc1
System.out.println(Arrays.toString(employees));
// → [Employee{id=100, name='rubytomato'}, Employee{id=200, name='garnetpepper'}, Employee{id=300, name='rubytomato'}, Employee{id=400, name='rubellitebeets'}]
** If null **
If the array is null, NullPointerException will not be thrown and the string "null" will be printed.
Example
Employee[] employees = null;
System.out.println(Arrays.toString(employees));
// → null
Returns the string representation of the array passed as an argument. For multidimensional arrays. If the array is null, the string "null" is returned.
deepToString
public static String deepToString(Object[] a)
Example
Employee[][] employees = new Employee[][] {
{
new Employee(100L, "rubytomato"),
new Employee(200L, "garnetpepper")
},
{
new Employee(300L, "spinelginger"),
new Employee(400L, "rubellitebeets")
}
;
System.out.println(Arrays.toString(employees));
// → [[Lcom.example.Employee;@1b4fb997, [Lcom.example.Employee;@deb6432]
System.out.println(Arrays.deepToString(employees));
// → [[Employee{id=100, name='rubytomato'}, Employee{id=200, name='garnetpepper'}], [Employee{id=300, name='spinelginger'}, Employee{id=400, name='rubellitebeets'}]]
** If null **
If the array is null, NullPointerException will not be thrown and the string "null" will be printed.
Example
Employee[][] employees = null;
System.out.println(Arrays.deepToString(employees));
// → null
Introduction version Java 1.8 </ font>
Removes elements from the collection that match the filter criteria passed in the argument.
removeIf
default boolean removeIf(Predicate<? super E> filter)
Example
List<String> fruits = new ArrayList<>();
Collections.addAll(fruits, "chocolate vine", "fig tree", "blackcurrant", "bramble",
"silverberry", "mulberry", "cranberry", "lingonberry", "pomegranate", "seaberry",
"jujube", "japanese bush cherry", "bilberry", "redcurrant", "grape");
// "berry"Delete elements ending in
fruits.removeIf(name -> name.endsWith("berry"));
System.out.println(fruits);
// → [chocolate vine, fig tree, blackcurrant, bramble, pomegranate, jujube, japanese bush cherry, redcurrant, grape]
Leaves the same elements as the collection elements you pass as arguments. Remove the unmatched elements from the collection.
retainAll
boolean retainAll(Collection<?> c)
Example
List<String> jewels = new ArrayList<>();
Collections.addAll(jewels, "amber", "aquamarine", "citrine", "garnet", "rubellite", "ruby",
"sapphire", "sinhalight", "spinel", "tanzanite", "tourmaline");
System.out.println(jewels);
// → [amber, aquamarine, citrine, garnet, rubellite, ruby, sapphire, sinhalight, spinel, tanzanite, tourmaline]
List<String> red = Arrays.asList("ruby", "rubellite", "spinel", "garnet");
boolean modified = jewels.retainAll(red);
System.out.println(modified);
// → true
System.out.println(jewels);
// → [garnet, rubellite, ruby, spinel]
Introduction version Java 1.8 </ font>
Generate a stream from the collection.
stream
default Stream<E> stream()
Example
List<String> lists = new ArrayList<>();
Collections.addAll(lists, "ruby", "garnet", "spinel");
lists.stream()
.map(String::toUpperCase)
.forEach(System.out::println);
// → RUBY
// → GARNET
// → SPINEL
Generate an array from the collection.
toArray
<T> T[] toArray(T[] a)
Example
List<String> lists = new ArrayList<>();
Collections.addAll(lists, "ruby", "garnet", "spinel");
//From List to array
String[] arrays = lists.toArray(new String[0]);
System.out.println(Arrays.toString(arrays));
// → [ruby, garnet, spinel]
Add the element specified by the second argument to the position of the index specified by the first argument.
add
void add(int index, E element)
Example
List<String> lists = new ArrayList<>();
Collections.addAll(lists, "Louis", "Keith", "Charles", "Williams", "Michael", "Ronald");
// index=Add element at position 3
lists.add(3, "Darryl");
System.out.println(lists);
// → [Louis, Keith, Charles, Darryl, Williams, Michael, Ronald]
Add to the top of the list
lists.add(0, "Darryl");
Add to the end of the list
lists.add(lists.size(), "Darryl");
The element of the collection specified by the second argument is added to the position of the index specified by the first argument.
addAll
boolean addAll(int index, Collection<? extends E> c)
Example
List<String> lists = new ArrayList<>();
Collections.addAll(lists, "Louis", "Keith", "Charles", "Williams", "Michael", "Ronald");
System.out.println(lists);
// → [Louis, Keith, Charles, Williams, Michael, Ronald]
List<String> others = Arrays.asList("Darryl", "Ian", "Tony");
lists.addAll(3, others);
System.out.println(lists);
// → [Louis, Keith, Charles, Darryl, Ian, Tony, Williams, Michael, Ronald]
Replace the index element specified in the first argument with the element specified in the second argument.
set
E set(int index, E element)
Example
List<String> lists = new ArrayList<>();
Collections.addAll(lists, "Louis", "Keith", "Charles", "Williams", "Michael", "Ronald");
String oldValue = lists.set(3, "Darryl");
System.out.println(oldValue);
// → Williams
System.out.println(lists);
// → [Louis, Keith, Charles, Darryl, Michael, Ronald]
Introduction version Java 1.8 </ font>
The operation result of operator passed to the argument is applied to each element and replaced with the result.
replaceAll
default void replaceAll(UnaryOperator<E> operator)
Example
List<String> lists = new ArrayList<>();
Collections.addAll(lists, "Louis", "Keith", "Charles", "Williams", "Michael", "Ronald");
System.out.println(lists);
// → [Louis, Keith, Charles, Williams, Michael, Ronald]
lists.replaceAll(s -> String.join("", "[", s.toUpperCase(), "]"));
System.out.println(lists);
// → [[LOUIS], [KEITH], [CHARLES], [WILLIAMS], [MICHAEL], [RONALD]]
Deletes the index element specified by the argument from the collection.
remove
E remove(int index)
Example
List<String> lists = new ArrayList<>();
Collections.addAll(lists, "Louis", "Keith", "Charles", "Williams", "Michael", "Ronald");
String value = lists.remove(3);
System.out.println(value);
// → Williams
System.out.println(lists);
// → [Louis, Keith, Charles, Michael, Ronald]
```
[sort](https://docs.oracle.com/javase/jp/8/docs/api/java/util/List.html#sort-java.util.Comparator-)
<font color = "blue"> Introduction version Java 1.8 </ font>
Sort the List using the comparator passed as an argument.
#### **`sort`**
```text
default void sort(Comparator<? super E> c)
```
#### **`Example`**
```java
List<String> lists = new ArrayList<>();
Collections.addAll(lists, "AAAA", "BBBB", "CCC", "DDD", "EE", "FFFFF", "AAAA", "BBB");
// String.Sort by the result of compareTo
lists.sort(String::compareTo);
System.out.println(lists);
// → [AAAA, AAAA, BBB, BBBB, CCC, DDD, EE, FFFFF]
```
#### **`Example`**
```java
List<String> lists = new ArrayList<>();
Collections.addAll(lists, "AAAA", "BBBB", "CCC", "DDD", "EE", "FFFFF", "AAAA", "BBB");
//Sort by string length.
lists.sort(Comparator.comparing(String::length));
System.out.println(lists);
// → [EE, CCC, DDD, BBB, AAAA, BBBB, AAAA, FFFFF]
```
#### **`Example`**
```java
List<String> lists = new ArrayList<>();
Collections.addAll(lists, "AAAA", "BBBB", "CCC", "DDD", "EE", "FFFFF", "AAAA", "BBB");
//String length+ String.Sort by the result of compareTo
lists.sort(Comparator.comparing(String::length)
.thenComparing(String::compareTo));
System.out.println(lists);
// → [EE, BBB, CCC, DDD, AAAA, AAAA, BBBB, FFFFF]
```
[ArrayList](https://docs.oracle.com/javase/jp/8/docs/api/java/util/ArrayList.html)
## Generate a new ArrayList from the collection
Generate an ArrayList from the collection passed to the constructor arguments.
#### **`constructor`**
```text
public ArrayList(Collection<? extends E> c)
```
** Set to ArrayList **
#### **`Example`**
```java
Set<String> sets = new HashSet<>();
Collections.addAll(sets, "Louis", "Keith", "Charles", "Williams", "Michael", "Ronald");
//Generate ArrayList from Set
List<String> lists = new ArrayList<>(sets);
System.out.println(lists);
// → [Charles, Keith, Williams, Ronald, Michael, Louis]
```
[Set](https://docs.oracle.com/javase/jp/8/docs/api/java/util/Set.html)
There is no method unique to the Set interface, so I will omit it.
[HashSet](https://docs.oracle.com/javase/jp/8/docs/api/java/util/HashSet.html)
## Generate a new HashSet from the collection
Generate a HashSet from the collection passed to the constructor arguments.
#### **`constructor`**
```text
public HashSet(Collection<? extends E> c)
```
** List to HashSet **
#### **`Example`**
```java
List<String> lists = new ArrayList<>();
Collections.addAll(lists, "Louis", "Keith", "Charles", "Williams", "Michael", "Ronald");
//Generate HashSet from List
Set<String> sets = new HashSet<>(lists);
System.out.println(sets);
// → [Charles, Keith, Williams, Ronald, Michael, Louis]
```
[EnumSet](https://docs.oracle.com/javase/jp/8/docs/api/java/util/EnumSet.html)
<font color = "green"> Introduction version Java 1.5 </ font>
[allOf](https://docs.oracle.com/javase/jp/8/docs/api/java/util/EnumSet.html#allOf-java.lang.Class-)
Generates an EnumSet consisting of all enumerators of the enumeration names passed as arguments.
#### **`allOf`**
```text
public static <E extends Enum<E>> EnumSet<E> allOf(Class<E> elementType)
```
#### **`Example`**
```java
EnumSet<DeepPurple> enums = EnumSet.allOf(DeepPurple.class);
System.out.println(enums);
// → [IanGillan, SteveMorse, RogerGlover, IanPaice, DonAirey]
```
[copyOf](https://docs.oracle.com/javase/jp/8/docs/api/java/util/EnumSet.html#copyOf-java.util.Collection-)
Generate an EnumSet from the Collection passed as an argument.
#### **`copyOf`**
```text
public static <E extends Enum<E>> EnumSet<E> copyOf(Collection<E> c)
```
#### **`Example`**
```java
Set<DeepPurple> sets = new HashSet<>();
Collections.addAll(sets, DeepPurple.IanGillan, DeepPurple.IanPaice);
EnumSet<DeepPurple> enums = EnumSet.copyOf(sets);
System.out.println(enums);
// → [IanGillan, IanPaice]
```
#### **`Example`**
```java
List<DeepPurple> lists = new ArrayList<>();
Collections.addAll(lists, DeepPurple.IanGillan, DeepPurple.IanPaice);
EnumSet<DeepPurple> enums = EnumSet.copyOf(lists);
System.out.println(enums);
// → [IanGillan, IanPaice]
```
[noneOf](https://docs.oracle.com/javase/jp/8/docs/api/java/util/EnumSet.html#noneOf-java.lang.Class-)
Generates an empty EnumSet of type enumeration to pass as an argument.
#### **`noneOf`**
```text
public static <E extends Enum<E>> EnumSet<E> noneOf(Class<E> elementType)
```
#### **`Example`**
```java
EnumSet<DeepPurple> enums = EnumSet.noneOf(DeepPurple.class);
System.out.println(enums);
// → []
```
[of](https://docs.oracle.com/javase/jp/8/docs/api/java/util/EnumSet.html#of-E-)
Generates an EnumSet consisting of enumerators to pass as arguments.
#### **`of`**
```text
public static <E extends Enum<E>> EnumSet<E> of(E e)
public static <E extends Enum<E>> EnumSet<E> of(E e1, E e2)
public static <E extends Enum<E>> EnumSet<E> of(E e1, E e2, E e3)
public static <E extends Enum<E>> EnumSet<E> of(E e1, E e2, E e3, E e4)
public static <E extends Enum<E>> EnumSet<E> of(E e1, E e2, E e3, E e4, E e5)
```
#### **`of`**
```text
@SafeVarargs
public static <E extends Enum<E>> EnumSet<E> of(E first, E... rest)
```
#### **`Example`**
```java
EnumSet<DeepPurple> enums = EnumSet.of(DeepPurple.RogerGlover, DeepPurple.DonAirey, DeepPurple.SteveMorse);
System.out.println(enums);
// → [SteveMorse, RogerGlover, DonAirey]
```
[Map](https://docs.oracle.com/javase/jp/8/docs/api/java/util/Map.html)
> [Why does Map not inherit from Collection? ](https://docs.oracle.com/javase/jp/8/docs/technotes/guides/collections/designfaq.html#a14)
> This is by design. I think the mapping is not a collection and the collection is not a mapping. Therefore, it makes little sense for Map to inherit the Collection interface and vice versa.
[compute](https://docs.oracle.com/javase/jp/8/docs/api/java/util/Map.html#compute-K-java.util.function.BiFunction-)
<font color = "blue"> Introduction version Java 1.8 </ font>
Apply the function passed in the 2nd argument to the value mapped to the key specified in the 1st argument, update the key value with the calculation result and return it.
If the key is not mapped, the value is calculated as null.
If the function returns null, the entry will be deleted.
#### **`compute`**
```text
default V compute(K key,
BiFunction<? super K,? super V,? extends V> remappingFunction)
```
#### **`Example`**
```java
Map<String, String> maps = new HashMap<>();
maps.put("ruby", "tomato");
maps.put("garnet", "pepper");
maps.put("spinel", "ginger");
maps.put("rubellite", null);
//Functions that are executed with or without mapping
BiFunction<String, String, String> remapping = (key, val) -> {
if (val == null) {
//This example returns a string,
//For example, you can execute processing such as searching the value from the DB with key.
return "UNKNOWN";
}
return val.toUpperCase();
};
//Mapped
String value = maps.compute("ruby", remapping);
System.out.println(value);
// → TOMATO
//Mapped to null
value = maps.compute("rubellite", remapping);
System.out.println(value);
// → UNKNOWN
//Not mapped
value = maps.compute("sapphire", remapping);
System.out.println(value);
// → UNKNOWN
System.out.println(maps);
// → {spinel=ginger, rubellite=UNKNOWN, garnet=pepper, sapphire=UNKNOWN, ruby=TOMATO}
```
[computeIfAbsent](https://docs.oracle.com/javase/jp/8/docs/api/java/util/Map.html#computeIfAbsent-K-java.util.function.Function-)
<font color = "blue"> Introduction version Java 1.8 </ font>
If the value is not mapped (or null is mapped) to the key specified by the first argument, the calculation result of the function passed by the second argument is updated as the key value and returned.
If the key has a value mapped, the map will not be updated and the key value will be returned.
If the function returns null, the entry will not be saved.
#### **`computeIfAbsent`**
```text
default V computeIfAbsent(K key,
Function<? super K,? extends V> mappingFunction)
```
#### **`Example`**
```java
Map<String, String> maps = new HashMap<>();
maps.put("ruby", "tomato");
maps.put("garnet", "pepper");
maps.put("spinel", "ginger");
maps.put("rubellite", null);
//Function executed when a non-null value is not mapped to the key
Function<String, String> mapping = (key) -> {
//This example returns a string,
//For example, you can execute processing such as searching the value from the DB with key.
return "UNKNOWN";
};
//The function is not executed because it is mapped
String value = maps.computeIfAbsent("ruby", mapping);
System.out.println(value);
// → tomato
//Since it is mapped to null, it executes the function and returns the result
value = maps.computeIfAbsent("rubellite", mapping);
System.out.println(value);
// → UNKNOWN
//Since it is not mapped, it executes the function and returns the result
value = maps.computeIfAbsent("sapphire", mapping);
System.out.println(value);
// → UNKNOWN
System.out.println(maps);
// → {spinel=ginger, rubellite=UNKNOWN, garnet=pepper, sapphire=UNKNOWN, ruby=tomato}
```
[computeIfPresent](https://docs.oracle.com/javase/jp/8/docs/api/java/util/Map.html#computeIfPresent-K-java.util.function.BiFunction-)
<font color = "blue"> Introduction version Java 1.8 </ font>
If a value other than null is mapped to the key specified by the first argument, the function passed by the second argument is applied, the key value is updated with the calculation result, and it is returned.
If no value is mapped to the key, the function will not be executed and the map will not be updated.
If the function returns null, the entry will be deleted.
#### **`computeIfPresent`**
```text
default V computeIfPresent(K key,
BiFunction<? super K,? super V,? extends V> remappingFunction)
```
#### **`Example`**
```java
Map<String, String> maps = new HashMap<>();
maps.put("ruby", "tomato");
maps.put("garnet", "pepper");
maps.put("spinel", "ginger");
maps.put("rubellite", null);
//Function executed when a non-null value is mapped to the key
BiFunction<String, String, String> remapping = (key, val) -> {
return val.toUpperCase();
};
//Since it is mapped, it executes the function and returns the result
String value = maps.computeIfPresent("ruby", remapping);
System.out.println(value);
// → TOMATO
//The function is not executed because it is mapped to null
value = maps.computeIfPresent("rubellite", remapping);
System.out.println(value);
// → null
//The function is not executed because it is not mapped
value = maps.computeIfPresent("sapphire", remapping);
System.out.println(value);
// → null
System.out.println(maps);
// → {spinel=ginger, rubellite=null, garnet=pepper, ruby=TOMATO}
```
[forEach](https://docs.oracle.com/javase/jp/8/docs/api/java/util/Map.html#forEach-java.util.function.BiConsumer-)
<font color = "blue"> Introduction version Java 1.8 </ font>
Executes a function passed as an argument for each entry in the map.
#### **`forEach`**
```text
default void forEach(BiConsumer<? super K,? super V> action)
```
#### **`Example`**
```java
Map<String, String> maps = new HashMap<>();
maps.put("ruby", "tomato");
maps.put("garnet", "pepper");
maps.put("spinel", "ginger");
maps.put("rubellite", "beets");
maps.forEach((key, val) -> {
System.out.println("key=" + key + ", value=" + val);
});
// → key=spinel, value=ginger
// → key=rubellite, value=beets
// → key=garnet, value=pepper
// → key=ruby, value=tomato
```
[merge](https://docs.oracle.com/javase/jp/8/docs/api/java/util/Map.html#merge-K-V-java.util.function.BiFunction-)
<font color = "blue"> Introduction version Java 1.8 </ font>
Maps the value passed in the 2nd argument when the value is not mapped to the key specified in the 1st argument (or null is mapped).
If the key is mapped, replace the value with the calculation result of the function passed in the third argument. If the function returns null, delete the entry.
#### **`merge`**
```text
default V merge(K key, V value,
BiFunction<? super V,? super V,? extends V> remappingFunction)
```
#### **`Example`**
```java
Map<String, String> maps = new HashMap<>();
maps.put("ruby", "tomato");
maps.put("garnet", "pepper");
maps.put("spinel", "ginger");
maps.put("rubellite", null);
Map<String, String> otherMaps = new HashMap<>();
otherMaps.put("rubellite", "BEETS");
otherMaps.put("ruby", "TOMATO");
otherMaps.put("sapphire", "SPINACH");
otherMaps.forEach((key, value) -> {
maps.merge(key, value, (oldVal, newVal) -> {
return oldVal + " -> " + newVal;
});
});
System.out.println(maps);
// → {spinel=ginger, rubellite=BEETS, garnet=pepper, sapphire=SPINACH, ruby=tomato -> TOMATO}
```
[putIfAbsent](https://docs.oracle.com/javase/jp/8/docs/api/java/util/Map.html#putIfAbsent-K-V-)
<font color = "blue"> Introduction version Java 1.8 </ font>
If the value is not mapped to the key specified by the first argument (or null is mapped), the value of the key is updated with the value passed by the second argument.
If a non-null value is already mapped, the map will not be updated.
#### **`putIfAbsent`**
```text
default V putIfAbsent(K key, V value)
```
#### **`Example`**
```java
Map<String, String> maps = new HashMap<>();
maps.put("ruby", "tomato");
maps.put("garnet", "pepper");
maps.put("spinel", "ginger");
maps.put("rubellite", null);
//Update if mapped to null
String value = maps.putIfAbsent("rubellite", "BEETS");
System.out.println(value);
// → null
//Does not update if mapped
value = maps.putIfAbsent("ruby", "TOMATO");
System.out.println(value);
// → tomato
//If it is not mapped, it will be mapped with an argument
value = maps.putIfAbsent("sapphire", "SPINACH");
System.out.println(value);
// → null
System.out.println(maps);
// → {spinel=ginger, rubellite=BEETS, garnet=pepper, ruby=tomato, sapphire=SPINACH}
```
[remove](https://docs.oracle.com/javase/jp/8/docs/api/java/util/Map.html#remove-java.lang.Object-java.lang.Object-)
<font color = "blue"> Introduction version Java 1.8 </ font>
If the value specified in the second argument is mapped to the key specified in the first argument (including the case where the value is null), that entry is deleted.
#### **`remove`**
```text
default boolean remove(Object key, Object value)
```
#### **`Example`**
```java
Map<String, String> maps = new HashMap<>();
maps.put("ruby", "tomato");
maps.put("garnet", "pepper");
maps.put("spinel", "ginger");
maps.put("rubellite", "beets");
maps.put("sapphire", null);
boolean modified = maps.remove("ruby", "TOMATO");
System.out.println(modified);
// → false
modified = maps.remove("ruby", "tomato");
System.out.println(modified);
// → true
modified = maps.remove("sapphire", null);
System.out.println(modified);
// → true
System.out.println(maps);
// → {spinel=ginger, rubellite=beets, garnet=pepper}
```
[replace](https://docs.oracle.com/javase/jp/8/docs/api/java/util/Map.html#replace-K-V-)
<font color = "blue"> Introduction version Java 1.8 </ font>
If the key specified in the first argument is mapped (including the case where the value is null), replace it with the value passed in the second argument.
Does not update the map if the key is not mapped.
#### **`replace`**
```text
default V replace(K key, V value)
```
#### **`Example`**
```java
Map<String, String> maps = new HashMap<>();
maps.put("ruby", "tomato");
maps.put("garnet", "pepper");
maps.put("spinel", "ginger");
maps.put("rubellite", "beets");
String oldValue = maps.replace("ruby", "TOMATO");
System.out.println(oldValue);
// → tomato
oldValue = maps.replace("sapphire", "spinach");
System.out.println(oldValue);
// → null
System.out.println(maps);
// → {spinel=ginger, rubellite=beets, garnet=pepper, ruby=TOMATO}
```
[replaceAll](https://docs.oracle.com/javase/jp/8/docs/api/java/util/Map.html#replaceAll-java.util.function.BiFunction-)
<font color = "blue"> Introduction version Java 1.8 </ font>
Replace the value with the operation result of the function passed to the argument.
#### **`replaceAll`**
```text
default void replaceAll(BiFunction<? super K,? super V,? extends V> function)
```
#### **`Example`**
```java
Map<String, String> maps = new HashMap<>();
maps.put("ruby", "tomato");
maps.put("garnet", "pepper");
maps.put("spinel", "ginger");
maps.put("rubellite", "beets");
maps.put("sapphire", null);
maps.replaceAll((key, value) -> {
if (value == null) {
return "UNKNOWN";
}
return value.toUpperCase();
});
System.out.println(maps);
// → {spinel=GINGER, rubellite=BEETS, garnet=PEPPER, ruby=TOMATO, sapphire=UNKNOWN}
```
[HashMap](https://docs.oracle.com/javase/jp/8/docs/api/java/util/HashMap.html)
## Generate a new HashMap from Map
Generate a new HashMap from the map you pass to the constructor arguments.
#### **`constructor`**
```text
public HashMap(Map<? extends K,? extends V> m)
```
** Map to HashMap **
#### **`Example`**
```java
Map<String, String> maps = new HashMap<>();
maps.put("ruby", "tomato");
maps.put("garnet", "pepper");
maps.put("spinel", "ginger");
//Generate a new HashMap
Map<String, String> newMaps = new HashMap<>(maps);
newMaps.put("rubellite", "beets");
System.out.println(maps);
// → {spinel=ginger, garnet=pepper, ruby=tomato}
System.out.println(newMaps);
// → {spinel=ginger, garnet=pepper, ruby=tomato, rubellite=beets}
```
[EnumMap](https://docs.oracle.com/javase/jp/8/docs/api/java/util/EnumMap.html)
<font color = "green"> Introduction version Java 1.5 </ font>
## Generate a new EnumMap from Map
Generates a new EnumMap from the map passed to the constructor arguments.
#### **`constructor`**
```text
public EnumMap(Map<K,? extends V> m)
```
#### **`Example`**
```java
Map<DeepPurple, LocalDate> maps = new HashMap<>();
maps.put(DeepPurple.IanGillan, LocalDate.of(1945, 8, 19));
maps.put(DeepPurple.SteveMorse, LocalDate.of(1954, 7, 28));
maps.put(DeepPurple.RogerGlover, LocalDate.of(1945, 11, 30));
maps.put(DeepPurple.IanPaice, LocalDate.of(1948, 6, 29));
maps.put(DeepPurple.DonAirey, LocalDate.of(1948, 6, 21));
EnumMap<DeepPurple, LocalDate> enums = new EnumMap<>(maps);
System.out.println(enums);
// → {IanGillan=1945-08-19, SteveMorse=1954-07-28, RogerGlover=1945-11-30, IanPaice=1948-06-29, DonAirey=1948-06-21}
```
## Generate Set from EnumMap
#### **`entrySet`**
```text
public Set<Map.Entry<K,V>> entrySet()
```
#### **`Example`**
```java
EnumMap<DeepPurple, LocalDate> enums = new EnumMap<>(DeepPurple.class);
enums.put(DeepPurple.IanGillan, LocalDate.of(1945, 8, 19));
enums.put(DeepPurple.SteveMorse, LocalDate.of(1954, 7, 28));
enums.put(DeepPurple.RogerGlover, LocalDate.of(1945, 11, 30));
enums.put(DeepPurple.IanPaice, LocalDate.of(1948, 6, 29));
enums.put(DeepPurple.DonAirey, LocalDate.of(1948, 6, 21));
Set<Map.Entry<DeepPurple, LocalDate>> sets = enums.entrySet();
System.out.println(sets);
// → [IanGillan=1945-08-19, SteveMorse=1954-07-28, RogerGlover=1945-11-30, IanPaice=1948-06-29, DonAirey=1948-06-21]
```
# [API added in Java 9](https://docs.oracle.com/javase/jp/9/docs/api/java/util/package-summary.html)
[Collections](https://docs.oracle.com/javase/jp/9/docs/api/java/util/Collections.html)
There are no additions.
[Arrays](https://docs.oracle.com/javase/jp/9/docs/api/java/util/Arrays.html)
equals
The following equals methods have been added.
```text
public static boolean equals(int[] a, int aFromIndex, int aToIndex,
int[] b, int bFromIndex, int bToIndex)
```
compare
Some compare methods have been added, such as:
```text
public static int compare(int[] a,
int[] b)
```
compareUnsigned
Some compareUnsigned methods have been added, such as:
```text
public static int compareUnsigned(int[] a,
int[] b)
```
mismatch
Some mismatch methods have been added, such as:
```text
public static int mismatch(int[] a,
int[] b)
```
[Collection](https://docs.oracle.com/javase/jp/9/docs/api/java/util/Collection.html)
There are no additions.
[List](https://docs.oracle.com/javase/jp/9/docs/api/java/util/List.html)
of
```text
static <E> List<E> of()
```
from e1 to e10
```text
static <E> List<E> of(E e1)
static <E> List<E> of(E e1, E e2, E e3, E e4, E e5, E e6, E e7, E e8, E e9, E e10)
```
```text
@SafeVarargs
static <E> List<E> of(E... elements)
```
[ArrayList](https://docs.oracle.com/javase/jp/9/docs/api/java/util/ArrayList.html)
There are no additions.
[Set](https://docs.oracle.com/javase/jp/9/docs/api/java/util/Set.html)
of
```text
static <E> Set<E> of()
```
from e1 to e10
```text
static <E> Set<E> of(E e1)
static <E> Set<E> of(E e1, E e2, E e3, E e4, E e5, E e6, E e7, E e8, E e9, E e10)
```
```text
@SafeVarargs
static <E> Set<E> of(E... elements)
```
[HashSet](https://docs.oracle.com/javase/jp/9/docs/api/java/util/HashSet.html)
There are no additions.
[EnumSet](https://docs.oracle.com/javase/jp/9/docs/api/java/util/EnumSet.html)
There are no additions.
[Map](https://docs.oracle.com/javase/jp/9/docs/api/java/util/Map.html)
of
```text
static <K,V> Map<K,V> of()
```
From k1, v1 to k10, v10
```text
static <K,V> Map<K,V> of(K k1, V v1)
static <K,V> Map<K,V> of(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5,
K k6, V v6, K k7, V v7, K k8, V v8, K k9, V v9, K k10, V v10)
```
ofEntries
```text
@SafeVarargs
static <K,V> Map<K,V> ofEntries(Map.Entry<? extends K,? extends V>... entries)
```
entry
```text
static <K,V> Map.Entry<K,V> entry(K k, V v)
```
[HashMap](https://docs.oracle.com/javase/jp/9/docs/api/java/util/HashMap.html)
There are no additions.
[EnumMap](https://docs.oracle.com/javase/jp/9/docs/api/java/util/EnumMap.html)
There are no additions.
# [API added in Java 10](https://docs.oracle.com/javase/jp/10/docs/api/java/util/package-summary.html)
[Collections](https://docs.oracle.com/javase/jp/10/docs/api/java/util/Collections.html)
There are no additions.
[Arrays](https://docs.oracle.com/javase/jp/10/docs/api/java/util/Arrays.html)
There are no additions.
[Collection](https://docs.oracle.com/javase/jp/10/docs/api/java/util/Collection.html)
There are no additions.
[List](https://docs.oracle.com/javase/jp/10/docs/api/java/util/List.html)
copyOf
```text
static <E> List<E> copyOf(Collection<? extends E> coll)
```
[ArrayList](https://docs.oracle.com/javase/jp/10/docs/api/java/util/ArrayList.html)
There are no additions.
[Set](https://docs.oracle.com/javase/jp/10/docs/api/java/util/Set.html)
copyOf
```text
static <E> Set<E> copyOf(Collection<? extends E> coll)
```
[HashSet](https://docs.oracle.com/javase/jp/10/docs/api/java/util/HashSet.html)
There are no additions.
[EnumSet](https://docs.oracle.com/javase/jp/10/docs/api/java/util/EnumSet.html)
There are no additions.
[Map](https://docs.oracle.com/javase/jp/10/docs/api/java/util/Map.html)
copyOf
```text
static <K,V> Map<K,V> copyOf(Map<? extends K,? extends V> map)
```
[HashMap](https://docs.oracle.com/javase/jp/10/docs/api/java/util/HashMap.html)
There are no additions.
[EnumMap](https://docs.oracle.com/javase/jp/10/docs/api/java/util/EnumMap.html)
There are no additions.
# Other review notes
* [Java NIO2 review memo](https://qiita.com/rubytomato@github/items/6880eab7d9c76524d112)
* August 15, 2017
* [Review notes for class java.util.Objects](https://qiita.com/rubytomato@github/items/ba38877ed5a00dd24f16)
* August 25, 2017
* [Review note of package java.time.temporal](https://qiita.com/rubytomato@github/items/e9325dd46aa11f1b8e2e)
* January 30, 2018
* [Review note of class java.util.Optional](https://qiita.com/rubytomato@github/items/92ac7944c830e54aa03d)
* March 22, 2018
Recommended Posts