1.Map转list
将Map的key转换为List
List<String> keyList = new ArrayList<>(map.keySet());
将Map的value转换为List
List<Integer> keyList = new ArrayList<>(map.values());
2. 将List转换为Map
Map<Integer, Integer> map = list.stream() .collect(Collectors.toMap(key -> key, value -> value , (v1, v2) -> v1)); key -> key, value -> value 返回的都是list处理的元素本身,也可以写为Function.identity()
(v1, v2) -> v1 作用:当 list转为map时,map的key重复不会覆盖之前的value而是报错Duplicate key 8 (attempted merging values {"itemId":417507,"vendorId":5816,"...
(v1, v2) -> v1 表示当出现重复的键时,选择保留原始的值 v1,而忽略新值 v2。
也可在出现重复的键时采取其他操作,例如:取最大值、取最小值或者进行求和等,可以在合并函数中编写相应的逻辑。例如,可以使用(v1, v2) -> Math.mix(v1, v2)来选择两个值中的最小值。
map是无序的,如果需要和list中的顺序一致可生成LinkedHashMap
Map<Integer, Integer> map = list.stream().collect(Collectors.toMap(key -> key, Function.identity() , (v1, v2) -> v1, LinkedHashMap::new));
将map的key和value反转,将相同value的key值收集生成list
Map<String, List<Integer>> groupByValueMap = groupByOrgMap.entrySet().stream() .collect(Collectors.groupingBy( Map.Entry::getValue, Collectors.mapping(Map.Entry::getKey, Collectors.toList()) ));
如果想将list 对象 分组 同一个对象的值生成一个list作为map的value
Map<String, List<Integer>> groupByOrgMap = storesList.stream().collect(Collectors.groupingBy( store -> "{\"itemId\":" + store.getItemId() + ",\"vendorId\":" + store.getVendorId() + ",\"shippingid\":" + store.getTypeid() + ",\"centerId\":" + store.getCenterId() + "}" , Collectors.mapping(ItemStoreVo::getOrgCode, Collectors.toList())));
3.给list添加序号
AtomicInteger countInt = new AtomicInteger(0);//从0开始 resultList.stream().peek(result -> result.setNumber(countInt.getAndIncrement())).collect(Collectors.toList());