HashMap对象的key、value值均可为null。
HahTable对象的key、value值均不可为null。
注意:stream方式转换封装map的value不能为null
封装Table
Table<String, String, Long> table = HashBasedTable.create();
dimensionDetailData.forEach(n->table.put(n.getName(),n.getDimensionValue(),n.getId()));
多层map封装Map
Map<String, Map<String, Long>> dimensionDetailData.stream().collect(Collectors.groupingBy(ETLDimensionDTO::getColumnName,
Collectors.toMap(ETLDimensionDTO::getDimensionValue, ETLDimensionDTO::getId)));
不想创建新封装类,使用元祖封装map的value
Map<Long, Pair<String, Long>> map = new HashMap<>();
for (DimensionValue obj : list) {
map.put(obj.getId(), Pair.of(obj.getDimensionValue(), obj.getDimensionId()));
}
指定key-value,value是对象本身,User->User 是一个返回本身的lambda表达式
Map<Integer,User> userMap2 = userList.stream().collect(Collectors.toMap(User::getId,User->User));
指定key-value,value是对象本身,Function.identity()是简洁写法,也是返回对象本身
Map<Integer,User> userMap3 = userList.stream().collect(Collectors.toMap(User::getId, Function.identity()));
指定key-value,value是对象本身,Function.identity()是简洁写法,也是返回对象本身,key 冲突的解决办法,这里选择第二个key覆盖第一个key。
Map<Integer,User> userMap4 = userList.stream().collect(Collectors.toMap(User::getId, Function.identity(),(key1,key2)->key2));
之前将Long数据,检查数据就不用转,不会出现数据转换异常
Map<String,String> dimensionMap= dimensionValues.stream().filter(m->m.getDimensionValue()!=null && null!=m.getId())
.collect(Collectors.toMap(m->m.getId().toString(), DimensionValue::getDimensionValue));
List
Map<String, List<Map<String, Object>>> groupList = mapList.stream()
.collect(Collectors.groupingBy(map -> map.get(ColumnConstants.GROUP_ID).toString()));
stream流把list中的某个属性转为set
Set<String> set= list.stream().map(实体::get属性).collect(Collectors.toSet));
带拼接多字段分组List< Object> 转 Map
Map<String, List<ProfitAndLossMapping>> collect = plMappingList.stream()
.collect(Collectors.groupingBy(m -> m.getLosType() + ":" + m.getRuleType()));
带拼接多字段分组List< Object> 转 Map
List<LosNameListByFy> losNameListByFIES = losNameListByFyMapper.selectList(null);
Map<String, String> losMap = losNameListByFIES.stream()
.collect(Collectors.toMap(o -> o.getFy() + ":" + o.getLos(), LosNameListByFy::getNewLos));
List< Object> 转 Map
Map<String, Long> reportOrgIdMap = reportOrgConfs.stream()
.collect(Collectors.groupingBy(m -> m.getReport() + ":" + m.getOrgId(), Collectors.counting()));
List< Object> 转 Map
Map<String, BigDecimal> avgMap = summaryInitList.stream()
.collect(HashMap::new, (map, item) -> map.put(item.getCombinedValue(), item.getValue()), HashMap::putAll);
Map<String,String> columnAndDimensionMap=dimensions.stream()
.filter(m->StringUtils.isNotBlank(m.getColumnName()))
.collect(Collectors.toMap(Dimension::getColumnName, Dimension::getName, (key1, key2) -> key1));
List< String> 转 Map
Map<String,String> reportMap=report.stream()
.filter(StringUtils::isNotBlank)
.collect(Collectors.toMap(Function.identity(),Function.identity()));
List< Object> 转 Map
Map<String, List<DictItemDetailVO>> map = list.stream()
.collect(Collectors.groupingBy(DictItemDetailVO::getDescription));
List< String>去重 拼接
List<String> list = Arrays.asList("AA", "BB", "CC", "BB", "CC", "AA", "AA");
long l = list.stream().distinct().count();
System.out.println("No. of distinct elements:"+l);
String output = list.stream().distinct().collect(Collectors.joining(","));
System.out.println(output);
List<Map<String, String>> list = new ArrayList<>();
{
Map<String, String> map = new HashMap<>();
map.put("id", "1");
map.put("name", "B");
map.put("age", "C");
list.add(map);
}
{
Map<String, String> map = new HashMap<>();
map.put("id", "1");
map.put("name", "E");
map.put("age", "F");
list.add(map);
}
//1.返回结果{"1","B"},{"2","E"}
Map<String, String> a = list.stream().collect(Collectors.toMap(l -> l.get("id"),
l -> l.get("name")));
//2.两种方法返回结果{"1":{"name":"B","id":"1","age":"C"},"2":{"name":"E","id":"2","age":"F"}}
Map<String, Map> b = list.stream().collect(Collectors.toMap(l -> l.get("id"), map -> map));
Map<String, Map> c = list.stream().collect(Collectors.toMap(l -> l.get("id"),
Function.identity()));
//3.重复key情况下处理方式返回结果{"1":{"name":"E","id":"1","age":"F"}}
Map<String, Map> d = list.stream().collect(Collectors.toMap(l -> l.get("id"),
Function.identity(), (key1, key2) -> key2));
//4.重复key情况下指定返回数据类型处理方式返回结果{"1":{"name":"E","id":"1","age":"F"}}
Map<String, Map> e = list.stream().collect(Collectors.toMap(l -> l.get("id"),
Function.identity(), (key1, key2) -> key2, LinkedHashMap::new));
//5.list根据key合并并转map;返回结果{"1":[{"name":"B","id":"1","age":"C"},{"name":"E","id":"1","age":"F"}]}
Map<String, List<Map>> lableGbType = list.stream()
.collect(Collectors.groupingBy(l -> (String) l.get("id")));
//6.根据key提取list中指定的值转List数组;返回结果["1","1"]
List<String> ids = list.stream().map(m -> (String) m.get("id"))
.collect(Collectors.toList());
//7.数组去重并转list
String[] str = "1,1,2,3,4,5,".split(",");
List<String> listNames = Arrays.stream(str).filter(name -> !isEmpty(name)).distinct().collect(Collectors.toList());
}
查数据
List<Map<String, Object>> prnInfo = xxxMapper.selectInfo(pars);
List<String> ids= prnInfo.stream().map(m -> m.get("id").toString()).collect(Collectors.toList());
**1.根据map的某个key分组**
Map<String, List<Map<String, Object>>> res= dataList.stream().collect(
groupingBy(map -> map.get("d").toString()));
获取type="ZC"的数据
----------------------------------------------------------------
List<Map<String, Object>> data = res.stream().
filter(
map -> (map.get("type")+"").equals("ZC")
).collect(Collectors.toList());
-----------------------------------------------------------------
List<Map<String, Object>> res = prnInfo .stream().filter(e ->Integer.parseInt(e.get("caseFlag").toString()) != 0)
.collect(Collectors.toList());
**2.根据某个key求对应value和**
int totalNums= prnInfo .stream().collect(Collectors.summingInt( e -> Integer.parseInt(e.get("num").toString())));
**3.根据map中的某个key的value值进行判断过滤**
List**4.对集合中的map做变更**
List<Map<String, Object>> res= prnInfo .stream().map(x -> {
x.put("encd", Double.parseDouble(x.get("rz")+"")-Double.parseDouble(x.get("tdz")+""));
return x;
}).collect(Collectors.toList());
**5.排序**
List<Map<String, Object>> res= prnInfo.stream().sorted((e1,e2) -> {
return -Double.compare(Double.valueOf(e1.get("num").toString()),Double.valueOf(e2.get("num").toString()));
}).collect(Collectors.toList());
res.sort(Comparator.comparing((Map<String, Object> h) -> (h.get("tm").toString())));
//排序可能对应字段数据为null导致空指针,需要先判断过滤一下
res.stream().filter(Objects::nonNull).filter((Map<String, Object> h)
-> (Objects.nonNull(h.get("fz")))).collect(Collectors.toList());
6.去重
List<String> res = prnInfo.stream().distinct().collect(Collectors.toList());
7.做统计
IntSummaryStatistics collect = list.stream().collect(Collectors.summarizingInt(Test::getId));
System.out.println("和:" + collect.getSum());
System.out.println("数量:" + collect.getCount());
System.out.println("最大值:" + collect.getMax());
System.out.println("最小值:" + collect.getMin());
System.out.println("平均值:" + collect.getAverage());
最大
double max = prnInfo.stream().mapToDouble(l -> ((BigDecimal) l.get("num")).doubleValue()).max().getAsDouble();
和
double sum = prnInfo.stream().mapToDouble(l -> ((BigDecimal) l.get("num")).doubleValue()).sum();
8.list-map转换
Map<String, Object> map = list.stream()
.collect(Collectors.toMap(i -> i.getName() + i.getUnitName(), j -> j, (k1, k2) -> k1));
------------------------------------------------------------------------
List<User> collect = map.entrySet().stream().map(item -> {
User user= new User();
user.setId(item.getKey());
user.setName(item.getValue());
return user;
}).collect(Collectors.toList());
遍历。。
users.stream().forEach(x->{
System.out.println(x);
});
下面这个场景用的也很多,List里面的a和b相等就把c属性相加,报表里面某些属性相等则求和等场景,可以先根据需要去重的多个字段进行分组,再计算返回
for (Map.Entry<String, List<DTO>> entry : beanList.parallelStream().collect(groupingBy(o -> (o.getId() + o.geCode()), Collectors.toList())).entrySet()) {
if(bitMap.contains(entry.getKey()) && entry.getValue().size()==1){
objects.add(entry.getValue().get(0));
}else{
List<DTO> transfer = entry.getValue();
transfer.stream().reduce((a, b) -> DTO.builder()
.irrCd(a.getIrrCd())
.id(a.getId())
.tm(a.getCode())
.build())
.ifPresent(objects::add);
}
}
1, 对象集合排序
//降序,根据创建时间降序;
List<User> descList = attributeList.stream()
.sorted(Comparator.comparing(User::getCreateTime,Comparator.nullsLast(Date::compareTo)).reversed())
.collect(Collectors.toList());
//升序,根据创建时间升序;
List<User> ascList = attributeList.stream()
.sorted(Comparator.comparing(User::getCreateTime,Comparator.nullsLast(Date::compareTo))).collect(Collectors.toList());
2, 数字排序
List<Integer> numbers = Arrays.asList(3, 2, 2, 3, 7, 3, 5);
//升序
List<Integer> ascList = numbers.stream().sorted().collect(Collectors.toList());
结果: [2, 2, 3, 3, 3, 5, 7]
//倒序
List<Integer> descList = numbers.stream().sorted((x, y) -> y - x).collect(Collectors.toList());
结果:[7, 5, 3, 3, 3, 2, 2]
3, 字符串排序
List<String> strList = Arrays.asList("a", "ba", "bb", "abc", "cbb", "bba", "cab");
//自然排序
List<String> ascList = strList.stream().sorted().collect(Collectors.toList());
结果:[a, abc, ba, bb, bba, cab, cbb]
//反转,倒序
ascList.sort(Collections.reverseOrder());
结果:[cbb, cab, bba, bb, ba, abc, a]
//直接反转集合
Collections.reverse(strList);
结果:[cab, bba, cbb, abc, bb, ba, a]
//HashMap是无序的,当我们希望有顺序地去存储key-value时,就需要使用LinkedHashMap了,排序后可以再转成HashMap。
//LinkedHashMap是继承于HashMap,是基于HashMap和双向链表来实现的。
//LinkedHashMap是线程不安全的。
Map<String,String> map = new HashMap<>();
map.put("a","123");
map.put("b","456");
map.put("z","789");
map.put("c","234");
//map根据value正序排序
LinkedHashMap<String, String> linkedMap1 = new LinkedHashMap<>();
map.entrySet().stream().sorted(Comparator.comparing(e -> e.getValue()))
.forEach(x -> linkedMap1.put(x.getKey(), x.getValue()));
结果:{a=123, c=234, b=456, z=789}
//map根据value倒序排序
LinkedHashMap<String, String> linkedMap2 = new LinkedHashMap<>();
map.entrySet().stream().sorted(Collections.reverseOrder(Map.Entry.comparingByValue()))
.forEach(x -> linkedMap2.put(x.getKey(), x.getValue()));
结果:{z=789, b=456, c=234, a=123}
//map根据key正序排序
LinkedHashMap<String, String> linkedMap3 = new LinkedHashMap<>();
map.entrySet().stream().sorted(Comparator.comparing(e -> e.getKey()))
.forEach(x -> linkedMap3.put(x.getKey(), x.getValue()));
结果:{a=123, b=456, c=234, z=789}
//map根据key倒序排序
LinkedHashMap<String, String> linkedMap4 = new LinkedHashMap<>();
map.entrySet().stream().sorted(Collections.reverseOrder(Map.Entry.comparingByKey()))
.forEach(x -> linkedMap4.put(x.getKey(), x.getValue()));
结果:{z=789, c=234, b=456, a=123}
1、指定key-value,value是对象中的某个属性值。
Map<Integer,String> userMap1 = userList.stream().collect(Collectors.toMap(User::getId,User::getName));
2、指定key-value,value是对象本身,User->User 是一个返回本身的lambda表达式
Map<Integer,User> userMap2 = userList.stream().collect(Collectors.toMap(User::getId,User->User));
3、指定key-value,value是对象本身,Function.identity()是简洁写法,也是返回对象本身
Map<Integer,User> userMap3 = userList.stream().collect(Collectors.toMap(User::getId, Function.identity()));
4、指定key-value,value是对象本身,Function.identity()是简洁写法,也是返回对象本身,key 冲突的解决办法,这里选择第二个key覆盖第一个key。
Map<Integer,User> userMap4 = userList.stream().collect(Collectors.toMap(User::getId, Function.identity(),(key1,key2)->key2));
5、将List根据某个属性进行分组,放入Map;然后组装成key-value格式的数据,分组后集合的顺序会被改变,所以事先设置下排序,然后再排序,保证数据顺序不变。
List<GoodsInfoOut> lst = goodsInfoMapper.getGoodsList();
Map<String, List<GoodsInfoOut>> groupMap = lst.stream().collect(Collectors.groupingBy(GoodsInfoOut::getClassificationOperationId));
List<HomeGoodsInfoOut> retList = groupMap.keySet().stream().map(key -> {
HomeGoodsInfoOut mallOut = new HomeGoodsInfoOut();
mallOut.setClassificationOperationId(key);
if(groupMap.get(key)!=null && groupMap.get(key).size()>0) {
mallOut.setClassificationName(groupMap.get(key).get(0).getClassificationName());
mallOut.setClassificationPic(groupMap.get(key).get(0).getClassificationPic());
mallOut.setClassificationSort(groupMap.get(key).get(0).getClassificationSort());
}
mallOut.setGoodsInfoList(groupMap.get(key));
return mallOut;
}).collect(Collectors.toList());
List<HomeGoodsInfoOut> homeGoodsInfoOutList = retList.stream().sorted(Comparator.comparing(HomeGoodsInfoOut::getClassificationSort)) .collect(Collectors.toList());
5、根据用户性别将数据 - 分组
Map<String, List<UserInfo>> groupMap = userList.stream().collect(Collectors.groupingBy(UserInfo::getSex()));
6、List实体转Map,想要有序的话,就使用以下操作(TreeMap 有序;Map 无序)
TreeMap<String, List<BillPollEntity>> ascMonthBillPollMap = s.stream()
.collect(Collectors.groupingBy(t -> t.getDrawTime()), TreeMap::new, Collectors.toList()));
//倒序MAP
NavigableMap<String, List<OpenActivityOut>> descMonthBillPollMap = ascMonthBillPollMap.descendingMap();
Map<String, List<BillPollEntity>> monthBillPollMap = s.stream().collect(Collectors.groupingBy(BillPollEntity::getDrawTime));
三,Map 转 List
Map
map1.put(“a”,“123”);
map1.put(“b”,“456”);
map1.put(“z”,“789”);
map1.put(“c”,“234”);
1、默认顺序
List list0 = map1.entrySet().stream()
.map(e -> new UserInfo(e.getValue(), e.getKey()))
.collect(Collectors.toList());
结果:[UserInfo(userName=123, mobile=a), UserInfo(userName=456, mobile=b), UserInfo(userName=234, mobile=c), UserInfo(userName=789, mobile=z)]
2、根据Key排序
List list1 = map1.entrySet().stream()
.sorted(Comparator.comparing(e -> e.getKey())).map(e -> new UserInfo(e.getKey(), e.getValue()))
.collect(Collectors.toList());
结果:[UserInfo(userName=a, mobile=123), UserInfo(userName=b, mobile=456), UserInfo(userName=c, mobile=234), UserInfo(userName=z, mobile=789)]
3、根据Value排序
List list2 = map1.entrySet().stream()
.sorted(Comparator.comparing(Map.Entry::getValue))
.map(e -> new UserInfo(e.getKey(), e.getValue()))
.collect(Collectors.toList());
结果:[UserInfo(userName=a, mobile=123), UserInfo(userName=c, mobile=234), UserInfo(userName=b, mobile=456), UserInfo(userName=z, mobile=789)]
3、根据Key排序
List list3 = map1.entrySet().stream()
.sorted(Map.Entry.comparingByKey())
.map(e -> new UserInfo(e.getKey(), e.getValue()))
.collect(Collectors.toList());
结果:[UserInfo(userName=a, mobile=123), UserInfo(userName=b, mobile=456), UserInfo(userName=c, mobile=234), UserInfo(userName=z, mobile=789)]
4、Map
// 取Map中的所有value
结果:List userInfoList = retMap.values().stream().collect(Collectors.toList());
// 取Map中所有key
结果:List strList = retMap.keySet().stream().collect(Collectors.toList());
四,从List中获取某个属性
//拿出所有手机号
List mobileList = userList.stream().map(RemindUserOut::getMobile).collect(Collectors.toList());
//拿出所有AppId,并去重
List appIdList = appIdList.stream().map(WechatWebViewDomain::getAppId).collect(Collectors.toList()).stream().distinct().collect(Collectors.toList());
//拿出集合中重复的billNo,【.filter(map->StringUtils.isNotEmpty(map.getBillNo()))】这是过滤掉为空的数据;否则,有空数据会抛异常
List repeatCodeList = resultList.stream().filter(map->StringUtils.isNotEmpty(map.getBillNo())).collect(Collectors.groupingBy(BillUploadIn::getBillNo, Collectors.counting())).entrySet().stream().filter(entry -> entry.getValue() > 1).map(Map.Entry::getKey).collect(Collectors.toList());
//拿出集合中几个属性拼接后的字符串
List strList = myList.stream().map(p -> p.getName() + “-” + p.getMobile()).collect(Collectors.toList());
五,筛选并根据属性去重
List uList = new ArrayList<>();
UserInfo u1 = new UserInfo(1,“小白”,“15600000000”);
UserInfo u2 = new UserInfo(2,“小黑”,“15500000000”);
uList.add(u1);
uList.add(u2);
//过滤名字是小白的数据
List list1= uList.stream()
.filter(b -> “小白”.equals(b.getUserName()))
.collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(b -> b.getId()))), ArrayList::new));
结果:list1===[UserInfo(id=1, userName=小白, mobile=15600000000)]
//根据ID去重
List list2= uList.stream()
.collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(b -> b.getId()))), ArrayList::new));
结果:list2===[UserInfo(id=1, userName=小白, mobile=15600000000), UserInfo(id=2, userName=小黑, mobile=15500000000)]
//整个数据去重
list = list.stream().distinct().collect(Collectors.toList());
六,计算;和,最大,最小,平均值。
List uList = new ArrayList<>();
UserInfo user1 = new UserInfo(1,“小白”,“15600000000”,10,new BigDecimal(10));
UserInfo user2 = new UserInfo(2,“小黑”,“15500000000”,15,new BigDecimal(20));
UserInfo user3 = new UserInfo(2,“小彩”,“15500000000”,88,new BigDecimal(99));
uList.add(user1);
uList.add(user2);
uList.add(user3);
//和
Double d1 = uList.stream().mapToDouble(UserInfo::getNum).sum();
结果:113.0
//最大
Double d2 = uList.stream().mapToDouble(UserInfo::getNum).max().getAsDouble();
结果:88.0
//最小
Double d3 = uList.stream().mapToDouble(UserInfo::getNum).min().getAsDouble();
结果:10.0
//平均值
Double d4 = uList.stream().mapToDouble(UserInfo::getNum).average().getAsDouble();
结果:37.666666666666664
//除了统计double类型,还有int和long,bigDecimal需要用到reduce求和
DecimalFormat df = new DecimalFormat(“0.00”);//保留两位小数点
//和;可过滤掉NULL值
BigDecimal add = uList.stream().map(UserInfo::getPrice).reduce(BigDecimal.ZERO, BigDecimal::add);
BigDecimal add = uList.stream().filter(s->t.getPrice()!=null).map(UserInfo::getPrice).reduce(BigDecimal.ZERO, BigDecimal::add)
System.out.println(df.format(add));
结果:129.00
//最大
Optional max = uList.stream().max((u1, u2) -> u1.getNum().compareTo(u2.getNum()));
System.out.println(df.format(max.get().getPrice()));
结果:99.00
//最小
Optional min = uList.stream().min((u1, u2) -> u1.getNum().compareTo(u2.getNum()));
System.out.println(df.format(min.get().getPrice()));
结果:10.00
//求和,还有mapToInt、mapToLong、flatMapToDouble、flatMapToInt、flatMapToLong
list.stream().mapToDouble(UserInfo::getNum).sum();
//最大
list.stream().mapToDouble(UserInfo::getNum).max();
//最小
list.stream().mapToDouble(UserInfo::getNum).min();
//平均值
list.stream().mapToDouble(UserInfo::getNum).average();
//获取N个List中,最大数组长度
List valueList = new ArrayList<>();
List tagList = valueList.stream().filter(v -> v.getTagList() != null && v.getTagList().size() > 0).map(OrderExcelOut::getTagList).collect(Collectors.toList());
Optional maxTagList = tagList.stream().max((u1, u2) -> Integer.valueOf(u1.size()).compareTo(u2.size()));
//数组中最长的数组
maxTagList.get().size();
原文链接:https://blog.csdn.net/y19910825/article/details/128107210