web123456

Detailed explanation of usage

1. Usage rules:

toMap(Function, Function) Returns a Collector that accumulates elements into a Map whose keys and values ​​are the result of applying the provided mapping function to the input element.

If the mapped key contains duplicates, an IllegalStateException is thrown when performing the collection operation. If the mapped keys may have duplicates, use toMap(Function, Function, BinaryOperator) instead.

2. Let's test it. First, create a new Sdudent class. The three attributes are id, name, and group

Then construct a List

        List<Student> list = new ArrayList<>();

        for (int i = 1; i < 4; i++) {

(new Student(i+"","student"+i));

        }

1. Convert list into a map with id as key, and value is the Sudent object corresponding to id:

Map<String, Student> map = ().collect((Student::getId, ()));

2. If there is a duplicate value for id, an error will be reported. Duplicate key xxx. The solution is:

Only take the next key and value:

Map<String, Student> map = ().collect((Student::getId,(),(oldValue,newValue) -> newValue))

Only take the previous key and value:

Map<String, Student> map = ().collect((Student::getId,(),(oldValue,newValue) -> oldValue))

3. Want to get a Map<String, String> corresponding to id and name:

Map<String, String> map = ().collect((Student::getId,Student::getName)); 

Note: name can be an empty string but cannot be null, otherwise a null pointer will be reported. Solution:

Map<String, String> map = ().collect((Student::getId, e->()==null?"":()));

If there are duplicate ids, two vaues can be mapped to the same id like this:

Map<String, String> map = ().collect((Student::getId,Student::getName,(e1,e2)->e1+","+e2));

4. Group Student collections into maps by group

Map<String, List<Student>> map = ().collect((Student::getGroup));

5. Filter and remove heavy weight, two List<Student>

List<Student> list1 = new ArrayList<>();

List<Student> list2= new ArrayList<>();

HashMap<String, String> hashMap = new HashMap<>();

for (int i = 1; i < 4; i++) {

(new Student(i+"","student"+i));

}

for (int i = 2; i < 5; i++) {

(new Student(i+"","student"+i));

}

Map<String, Student> map2 = ().collect((Student::getId,()));

//Fetch out the name of the Student object with id repeated in List1 and List2:

List<String> strings = ().map(Student::getId).filter(map2::containsKey).map(map2::get).map(Student::getName).collect(());

(strings);// Output [Student 2, Student 3]



Original link: /p/2b6927d95137