對Java8 stream的簡單實踐
阿新 • • 發佈:2018-12-07
最近學習很多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 voidsetName(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(); returnn; } @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); } }