Java8 heavy objects in the collection to repeat

Entity Class 1 using

@Data
@NoArgsConstructor
@AllArgsConstructor
@String
public class User(){
	private String userId;
	private String userName;
	private Integer userAge;
}

2 using deduplication Collectors.toMap

2.1 toMap to re-explain

List<User> userList = new ArrayList<>();
        userList.add(new User("a", "xiaoming",12));
        userList.add(new User("b", "xiaoming",13));
        userList.add(new User("d", "xiaoming",15));
        userList.add(new User("a", "xiaoming",14));
       
        System.out.println("利用Collectors.toMap去重:");
        //利用Collectors.toMap去重
        userList.stream()
                .collect(Collectors.toMap(User::getUserId, 
                			Function.identity(), (oldValue, newValue) -> oldValue))
                .values()
                .stream()
                .forEach(System.out::println); //打印

Output:

[{"userAge":12,"userId":"a","userName":"xiaoming"},
{"userAge":13,"userId":"b","userName":"xiaoming"},
{"userAge":15,"userId":"d","userName":"xiaoming"}]

Which Collectors.toMaprequires the use of three parameters version, the first two parameters are a keyMapperfunction is a valueMapperfunction, used toMapall know that the key to weight that the third parameter BinaryOperatorfunction interface.

This BinaryOperatorfunction receives two parameters, such as the above code, a oldValue, a newValue, literally, old first value, the second is the new value. When streamconstructing Map, will first call the get method Map of acquiring old value of the key corresponding to the node, if the value is null, no calling BinaryOperatorfunction, if not null, you will get the old and new values as parameters to the function performed, and then put into the return value of the function value as a new Map. If you do not understand, look at the source code it

2.2 Funcion.identity () explained

Java 8 allowed to join a specific method in the interface. There are two specific methods of the interface defaultmethods and staticmethods identity()is Functionan interface 静态方法.
Function.identity()A return output with the same input Lambdaexpression object, the form equivalent to the t -> tform of Lambdaexpression.
identity()Source JDK methods as follows:

static  Function identity() {
    return t -> t;
}

The following code, Task::getTitlerequires a taskand generates a header only one key
task -> taskis a return for their lambdaexpression, the embodiment returns a task

private static Map<String, Task> taskMap(List<Task> tasks) {
  return tasks.stream().collect(toMap(Task::getTitle, task -> task));
}

You can use Functionthe default interface methods identityto make the code above code more concise, more direct transfer of developer intent, the following is the use of the code identity function.

import static java.util.function.Function.identity;
private static Map<String, Task> taskMap(List<Task> tasks) {
  return tasks.stream().collect(toMap(Task::getTitle, identity()));
}

3 and using Collectors.toCollection TreeSet deduplication

List<User> userList = new ArrayList<>();
        userList.add(new User("a", "xiaoming",12));
        userList.add(new User("b", "xiaoming",13));
        userList.add(new User("d", "xiaoming",15));
        userList.add(new User("a", "xiaoming",14));
       
        System.out.println("利用Collectors.toMap去重:");
        //利用Collectors.toMap去重
        userList.stream()
                .collect(Collectors.toCollection(() ->
                	 new TreeSet<>(Comparator.comparing(User::getUserId))))
                .values()
                .stream()
                .forEach(System.out::println); //打印

Output:

[{"userAge":12,"userId":"a","userName":"xiaoming"},
{"userAge":13,"userId":"b","userName":"xiaoming"},
{"userAge":15,"userId":"d","userName":"xiaoming"}]

Using the TreeSetprinciple of de-emphasis, TreeSetinternal use is TreeMap, using the specified Comparatorcompare elements, if the elements are the same, new elements to replace the old elements,
TreeMapthe putway to put the elements, are interested can find their own source code
if you do not want to return TreeSettype, it can also be used Collectors.collectingAndThenconvert ArrayListcan also be used new ArrayList(set), the same principle, as follows:

List<Person> distinctList = personList.stream()
                .collect(Collectors.collectingAndThen(Collectors.toCollection(() 
                	-> new TreeSet<>(Comparator.comparing(User::getUserId))), ArrayList::new));
Published 334 original articles · won praise 186 · views 310 000 +

Guess you like

Origin blog.csdn.net/u012060033/article/details/103683494