JAVA objects in the deduplication List Value method

  JAVA objects in the deduplication List value, roughly divided into two cases, one is a List <String>, List <Integer> such, directly to the weight according to the value of the List, the other is a List <User> This , javabean List is stored in the object, we need to be compared to a value weight according to the List object or several values. Methods as below:

 

A, List <String>, List <Integer> deduplication target value.

This is the case, the process is relatively simple, the stream of new features JDK1.8 distinct methods, it can be processed directly.

1     List<String> list1 = Arrays.asList("a", "b", "c", "a", new String("c"));
2     list1.stream().distinct().forEach(System.out::println);
3 
4     List<Integer> list2 = Arrays.asList(1, 2, 3, 1, new Integer(2));
5     list2.stream().distinct().forEach(System.out::println);

 

Two, List <User> deduplication target value.

This, then, can not be directly compared List objects, require rewriting equals and hashCode method bean object, and to automatically re-set by placing Set, the following specific examples.

Object entity:

 1 @Data
 2 @AllArgsConstructor
 3 public class User {
 4     private String id;
 5     private String name;
 6     private int age;
 7 
 8     public boolean equals(Object obj) {
 9         User u = (User) obj;
10         return name.equals(u.name);
11     }
12 
13     public int hashCode() {
14         String in = name;
15         return in.hashCode();
16     }
17 }

By comparing the above examples is the name of the same, i.e. equal to that object.

 

1     List<User> userList = new ArrayList<>();
2     userList.add(new User("1", "peter", 18));
3     userList.add(new User("2", "stark", 25));
4     userList.add(new User("3", "peter", 22));
5     
6     Set<User> userSet = new HashSet<>(userList);
7     List<User> list = new ArrayList<>(userSet);
8     list.forEach(System.out::println);

Automatic de-emphasis (even if used above equals and hashCode methods) into the List by Set, and then back into the List can be.

 

Guess you like

Origin www.cnblogs.com/pcheng/p/10930944.html