先过滤在转换
List<String> organizationList = getUser().getOrganizationList().stream().filter(t -> t.getErpCode() != null)
.map(t -> t.getErpCode()).distinct().collect(Collectors.toList());
list快速转map
Map<String, GddResult> gddMap = gddList.stream().collect(Collectors.toMap(g -> g.getGoodsCode(), g -> g, (k1, k2) -> k1));
字典排序
List<String> list = new ArrayList<String>();
list.add("a2Y12345");
list.add("3X12345");
list.add("1Z12345");
List<String> disProductList = list.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(o -> o))), ArrayList::new));
list 先分组然后转map
Test t1= new Test("001","1","Y1","1");
Test t2= new Test("001","2","Y1","2");
Test t3= new Test("002","1","Y1","3");
Test t4= new Test("002","2","Y1","4");
Test t5= new Test("001","1","Y2","5");
Test t6= new Test("002","1","Y2","6");
List<Test> list = new ArrayList<>();
list.add(t1);
list.add(t2);
list.add(t3);
list.add(t4);
list.add(t5);
list.add(t6);
Map<String, Map<String, Map<String, String>>> collect = list.stream().collect(Collectors.groupingBy(Test::getOrgCode, Collectors.groupingBy(Test::getChannelId, Collectors.toMap(Test::getProductCode, Test::getD))));
System.out.println(JSON.toJSON(collect));
输出
{"001":{"1":{"Y1":"1","Y2":"5"},"2":{"Y1":"2"}},"002":{"1":{"Y1":"3","Y2":"6"},"2":{"Y1":"4"}}}
日期类型排序
List<Date> datas = new ArrayList<>();
String s1 = "2019-08-10 22:18:22";
String s2 = "2018-08-10 22:18:22";
String s3 = "2017-08-10 22:19:22";
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
datas.add(df.parse(s1));
datas.add(df.parse(s2));
datas.add(df.parse(s3));
datas.sort((a,b)-> b.compareTo(a));
datas.forEach(d->{
System.out.println(d);
});
对象类型排序
ss.sort((a, b) -> b.getAge() - a.getAge());
inventory.sort(comparing(Apple::getWeight).reversed());
//返回 对象集合以类属性一降序排序 注意两种写法
list.stream().sorted(Comparator.comparing(类::属性一).reversed());//先以属性一升序,结果进行属性一降序
list.stream().sorted(Comparator.comparing(类::属性一,Comparator.reverseOrder()));//以属性一降序
按照两个属性排序
//返回 对象集合以类属性一升序 属性二升序
list.stream().sorted(Comparator.comparing(类::属性一).thenComparing(类::属性二));
//返回 对象集合以类属性一降序 属性二升序 注意两种写法
list.stream().sorted(Comparator.comparing(类::属性一).reversed().thenComparing(类::属性二));//先以属性一升序,升序结果进行属性一降序,再进行属性二升序
list.stream().sorted(Comparator.comparing(类::属性一,Comparator.reverseOrder()).thenComparing(类::属性二));//先以属性一降序,再进行属性二升序
//根据机构,渠道,商品分组分组,最后的list中正常情况有且只有一个对象
Map<String, Map<String, Map<String, List<StockProductBuisnessDto>>>> lastPriceMap = lastPriceList.stream().collect(Collectors.groupingBy(StockProductBuisnessDto::getOrgCode, Collectors.groupingBy(StockProductBuisnessDto::getChannelId, Collectors.groupingBy(StockProductBuisnessDto::getProductCode))));
//分组后再提取某个属性做list
pList.stream().collect(Collectors.groupingBy(Person::getLession, Collectors.mapping(Person::getId, Collectors.toList())));