1.准备数据
public static List<Persion> getData(){ List<Persion> arrayList = new ArrayList<>(); arrayList.add(new Persion("李四","20","男")); arrayList.add(new Persion("王麻子","30","男")); arrayList.add(new Persion("wangwu","10","女")); arrayList.add(new Persion("wangwu","10","女")); arrayList.add(null); return arrayList; }
2.List对象转Map
public static void main(String[] args) { List<Persion> persions = getData(); //list对象转 Map<String,String> name 是key,age是value。 Map<String, String> stringMap = persions.stream().collect(Collectors.toMap(Persion::getName, Persion::getSex)); System.out.println("stringMap:"+stringMap); // 结果:stringMap:{李四=男, 王麻子=男, wangwu=女} }
3.List对象转Map对象并去重
public static void main(String[] args) { List<Persion> persions = getData(); Map<String, Persion> stringMap = persions.stream().collect(Collectors.toMap(Persion::getName, Function.identity(), (key1, key2) -> key2)); System.out.println("stringMap:"+stringMap); } //输出:stringMap:{李四=Persion{name='李四', age='20', sex='男'}, 王麻子=Persion{name='王麻子', age='30', sex='男'}, wangwu=Persion{name='wangwu', age='10', sex='女'}}
//收集对象本身并转换 Map<String, Persion> persionMap2 = persions.stream().collect(Collectors.toMap(Persion::getName, v -> new Persion(v.getName(),"","")));
4.List对象转List转Set转List<String> 都类似
public static void main(String[] args) { List<Persion> persions = getData(); List<Persion> persions1 = persions.stream().collect(Collectors.toList()); // list对象转list对象的属性 Set<String> collect2 = persions.stream().map(Persion::getName).collect(Collectors.toSet()); System.out.println("stringMap:"+collect2); // 结果:stringMap:stringMap:[李四, 王麻子, wangwu] }
5.多个字段排序 第一个字段降序,第二个字段升序
public static void main(String[] args) { List<Persion> persions = getData(); List<Persion> persions1 = persions.stream().sorted(Comparator.comparing(Persion::getAge).reversed().thenComparing(Persion::getAge)).collect(Collectors.toList()); System.out.println("stringMap:"+persions1); } // 结果:stringMap:[Persion{name='王麻子', age='30', sex='男'}, Persion{name='李四', age='20', sex='男'}, Persion{name='wangwu', age='10', sex='女'}, Persion{name='wangwu', age='10', sex='女'}]
6.根据某个字段分组
public static void main(String[] args) { List<Persion> persions = getData(); Map<String, List<Persion>> collect3 = persions.stream().collect(Collectors.groupingBy(Persion::getAge)); System.out.println("stringMap:"+collect3); } // 结果:stringMap:{30=[Persion{name='王麻子', age='30', sex='男'}], 20=[Persion{name='李四', age='20', sex='男'}], 10=[Persion{name='wangwu', age='10', sex='女'}, Persion{name='wangwu', age='10', sex='女'}]}
7.去除空元素
public static void main(String[] args) { List<Persion> persions = getData(); boolean removeAll = persions.removeAll(Collections.singleton(null)); System.out.println("stringMap:"+removeAll); System.out.println("persions:"+persions); } //结果:stringMap:true //persions:[Persion{name='李四', age='20', sex='男'}, Persion{name='王麻子', age='30', sex='男'}, Persion{name='wangwu', age='10', sex='女'}, Persion{name='wangwu', age='10', sex='女'}]