有关map的stream使用
根据多个list之间的判断
核心api-集合分组
Collectors.groupingBy(MerchPO::getType)
public static void main(String[] args) {
/**
* 需求背景
* 判断一个商户对应门店是否可以推送,门店类型:1:线上电商2:线下门店 3 其他
* 商户下必须是相同类型门店才可以推送。
* */
//1. 模拟数据
MerchPO merchPO1 = new MerchPO("001", "888", "1", 0);
MerchPO merchPO2 = new MerchPO("002", "888", "1", 0);
MerchPO merchPO3 = new MerchPO("003", "888", "1", 0);
List<MerchPO> list = CollUtil.newArrayList();
list.add(merchPO1);
list.add(merchPO2);
list.add(merchPO3);
Map<String, List<MerchPO>> collect =list.stream().collect(Collectors.groupingBy(MerchPO::getType));
if(collect.size()>1) {
System.out.println("线上和线下不能同时存在");
}else {
System.out.println("验证通过");
}
}
排序-先分组把分组排序-然后-把每个分组里也要排序
核心api-flatMap
public static void main(String[] args) {
/**
* 需求背景
* 获取更多门店: 门店类型:1:线上电商2:线下门店 3 其他
* 顺序: 线上,线下(如果是线下需要根据距离排序), 其他
* */
//1. 模拟数据
MerchPO merchPO1 = new MerchPO("001", "888", "1", 0);
MerchPO merchPO2 = new MerchPO("002", "888", "2", 0);
MerchPO merchPO3 = new MerchPO("003", "888", "1", 0);
MerchPO merchPO4 = new MerchPO("004", "888", "2", 12);
List<MerchPO> list = CollUtil.newArrayList();
list.add(merchPO1);
list.add(merchPO2);
list.add(merchPO3);
list.add(merchPO4);
//映射
// Map<String, MerchPO> collect = list.stream().collect(Collectors.toMap(MerchPO::getMid, v -> v));
// 分组
Map<String, List<MerchPO>> mapList = list.stream().collect(Collectors.groupingBy(MerchPO::getType));
// 分组-统计个数
// Map<String, Long> collect = list.stream().collect(Collectors.groupingBy(MerchPO::getType, Collectors.counting()));
mapList.entrySet().forEach(item -> {
System.out.println(item);
String key = item.getKey();
if(key.equals("2")) {
List<MerchPO> collect1 = item.getValue().stream().sorted(Comparator.comparing(MerchPO::getDistance)).collect(Collectors.toList());
item.setValue(collect1);
}
});
//分组并且线下排序完成
System.out.println(mapList);
// 把map转换成功2维 list,然后将2维list(双层的)转换成一维list
List<List<MerchPO>> list_2_wei = mapList.values().stream().collect(Collectors.toList());
System.out.println(list_2_wei);
List<MerchPO> collect_1_list = mapList.values().stream().flatMap(v -> v.stream()).collect(Collectors.toList());
System.out.println(collect_1_list);
// System.out.println(collect2);
// collect.entrySet().stream().sorted(Comparator.comparing(MerchPO::getType))
// System.out.println(collect);
//
}
是否foreach不能抛出异常
for(Iterator it = list.iterator(); it.hasNext();) {
throw new Exception("FDA");
}
list.stream().forEach(v -> {
throw new Exception("A");
});