最近学习很多Java8方面的新特性,特地做了一些简单的实践和总结。
import java.util.*; import java.util.stream.Collectors; public class StreamTest { static class User{ private String name; private int age; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public User(String name, int age) { this.name = name; this.age = age; } @Override public String toString() { return name; }
// 重写hashCode @Override public int hashCode() { int n = 31; n = n * 31 + age; n = n* 31 + name.hashCode(); return n; } @Override public boolean equals(Object obj) { if (!(obj instanceof User)) { return false; } User user1 = (User) obj; return this.name.equals(user1.name) && Integer.valueOf(age).equals(user1.age); } } public static void main(String[] args) { List<User> list = new ArrayList<>(); User user1 = new User("zdx", 12); User user2 = new User("zdx1", 12); User user3 = new User("zdx2", 18); User user4 = new User("zdx3", 22); list.add(user1); list.add(user2); list.add(user3); list.add(user4); // 将 Stream 转化为List 并且实现去重 List list1 = list.stream().distinct().collect(Collectors.toList()); list1.forEach(System.out::println); // 将 Stream 转化为 Map // 实现此方法需要注意添加进Map的的 key 值不可以重复,否则会抛出异常!!!! Map<String, Integer> map = list.stream().collect(Collectors.toMap(User::getName, User::getAge)); for (String key: map.keySet()) { System.out.println(key); } // 去重实现方法一 List<User> result = new LinkedList<>(); for (User user : list) { boolean b = result.stream().anyMatch(u -> u.name.equals(user.name)); if (!b) { result.add(user); } } result.forEach(System.out::println); // 利用HashSet实现list的去重 Set<User> set = new HashSet<>(list); set.forEach(System.out::println); } }