Java8--stream流操作對List、List的過濾處理經驗分享
應用場景(一):
1.對list<map>中map中某個指定的key的value的去重,得到新的list:去除了重複出現指定key的value值得map
示例:
要求:過濾掉電話相同的map
List<Map<String, Object>> mapList = new ArrayList<Map<String, Object>>();
Map<String, Object> mapStr1 = new HashMap<String, Object>();
mapStr1.put("name", "麗麗");
mapStr1.put("sex", "女");
mapStr1.put("age", 22);
mapStr1.put("tel", "110");
Map<String, Object> mapStr2 = new HashMap<String, Object>();
mapStr2.put("name", "麗麗");
mapStr2.put("sex", "女");
mapStr2.put("age", 23);
mapStr2.put("tel", "120");
Map<String, Object> mapStr3 = new HashMap<String, Object>();
mapStr3.put("name", "麗麗");
mapStr3.put("sex", "女");
mapStr3.put("age", 24);
mapStr3.put("tel", "110");
mapList.add(mapStr1);
mapList.add(mapStr2);
mapList.add(mapStr3);
ArrayList<Map<String, Object>> cs = mapList.stream()
.collect(Collectors
.collectingAndThen(Collectors
.toCollection(() -> new TreeSet<>(new Comparator<Map<String, Object>>() {
@Override //重寫比較器public int compare(Map<String, Object> o1, Map<String, Object> o2) {
if (o1.get("tel").equals(o2.get("tel"))) {
return 0;
}
return 1;
}
})), ArrayList::new));
//迴圈取出結果
System.out.println("======map========");
m.keySet().forEach(n -> System.out.println(n + "-->" + m.get(n)));
});
應用場景(二):
對list<T>中物件T的指定屬性的去重,比如唯一ID,tel,獲取新的list:去除了重複出現的指定屬性值的物件T
示例:
要求過濾掉電話相同的user
User u1 = new User(1, "小米1", "001號", "女", 21, "110");
User u2 = new User(2, "小米2", "002號", "男", 11, "120");
User u3 = new User(3, "小米3", "003號", "女", 21, "119");
User u4 = new User(4, "小米4", "004號", "女", 34, "110");
List<User> persons = Arrays.asList(u1, u2, u3, u4);
List<User> unique = persons.stream()
.collect(Collectors
.collectingAndThen(Collectors
.toCollection(() -> new TreeSet<>(Comparator
.comparing(User::getTel))), ArrayList::new));
//迴圈取出結果