background
- In recent work development, I have gradually gotten used to many usages of Stream in Java 8. It is very convenient and can also execute this stream in parallel. Let’s write a list map scenario I encountered yesterday.
Application of list to map in Java 8 stream
Common ways
1. Use methods to convert
public Map<Long, String> getIdNameMap(List<Account> accounts) {
return accounts.stream().collect(Collectors.toMap(Account::getId, Account::getUsername));
}
The first parameter is OK, and the second parameter is the value of value.
2. Collect the object entity itself
- During the development process, we also need to group the entities in our list according to one of the fields (such as id ->List). At this time, we need to set the value of the map to the entity itself.
public Map<Long, Account> getIdAccountMap(List<Account> accounts) {
return accounts.stream().collect(Collectors.toMap(Account::getId, account -> account));
}
account -> account is a lambda expression that returns itself. In fact, you can also use a default method () in the Function interface. This method returns its own object, which is more concise.
- Repeat key situation.
- When list is converted to map, the value as key may be repeated. At this time, the flow processing will throw an exception: :Duplicate key. At this time, you need to specify the key selection when the key conflicts in the toMap method. (Here is to select the second key to cover the first key)
public Map<String, Account> getNameAccountMap(List<Account> accounts) {
return ().collect((Account::getUsername, (), (key1, key2) -> key2));
}
- GroupingBy or partitioningBy
- GroupingBy method can also be used directly by grouping according to a field or attribute, which is very convenient.
Map<Integer, List<Person>> personGroups = Stream.generate(new PersonSupplier()).
limit(100).
collect(Collectors.groupingBy(Person::getAge));
Iterator it = personGroups.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<Integer, List<Person>> persons = (Map.Entry) it.next();
System.out.println("Age " + persons.getKey() + " = " + persons.getValue().size());
}
- partitioningBy can be understood as a special groupingBy, with the key values true and false. Of course, the parameters in the method are a judgment statement (a functional interface used for judgment)
Map<Boolean, List<Person>> children = Stream.generate(new PersonSupplier()).
limit(100).
collect(Collectors.partitioningBy(p -> p.getAge() < 18));
System.out.println("Children number: " + children.get(true).size());
System.out.println("Adult number: " + children.get(false).size());
Recommended good articles about using stream:
- I went here to read an article about stream by ibm, and got many usages that have not been encountered in streams. You guys can learn it. [/developerworks/cn/java/j-lo-java8streamapi/ ]