集合转map(key唯一)
List<Entity> entitys;
Map<String, Entity> entityMaps = entitys.stream().collect(Collectors.toMap(e -> "" + e.getId(), e -> e, (entity1, entity2) -> entity1));
集合转map,取某一字段作为value(key唯一)
List<Entity> entitys;
Map<String, Integer> sIMap = entitys.stream().collect(Collectors.toMap(Entity::getId, Entity::getTotalCount, (entity1, entity2) -> entity1));
集合转map,分组统计
List<Entity> entitys;
Map<String, Long> map = entitys.stream().collect(Collectors.groupingBy(Entity::getId, Collectors.counting()));
集合过滤filter
List<Entity> entitys;
entitys = entitys.stream().filter(s -> Constant.id.equals(s.getId())).collect(Collectors.toList());
集合分组groupingBy
List<Entity> entitys;
Map<String, List<Entity>> entitysMap = entitys.stream().collect(Collectors.groupingBy(Entity::getId));
Map<String, List<Entity>> entitysMap = entitys.stream().collect(Collectors.groupingBy(i -> i.getA() + "_" + i.getB()));
Map<String, List<Entity>> entitysMap = entitys.stream().collect(Collectors.groupingBy(
i -> {
if(i.getA() < 3) {
return "3";
}else {
return "other";
}
}
));
多级集合分组
Map<String, Map<String, List<Entity>>> entitysMap = entitys.stream().collect(Collectors.groupingBy(Entity::getId, Collectors.groupingBy(i -> {
if(i.getA() < 3) {
return "3";
}else {
return "other";
}
})));
集合取某一字段重组集合
List<Entity> entitys;
List<Long> ids = entitys.stream().flatMap(Collection::stream)
.map(Entity::getId).collect(Collectors.toList());
List<Long> ids = entitys.stream().map(s -> s.getId()).collect(Collectors.toList());
List根据某个字段求和
int sum = entitys.stream().collect(Collectors.summingInt(Entity::getNumber));
int ageSum = entitys.stream().mapToInt().sum(Entity::getNumber);
集合根据某一字段排序
List<Entity> entitys;
entitys = entitys.stream().sorted(Comparator.comparing(entitys::getId)).collect(Collectors.toList());
集合-Map根据排序
List<Entity> entitys;
entitys = entitys.stream().sorted(Comparator.comparing((Map m) -> (new BigDecimal(m.get("age").toString())))).collect(Collectors.toList());
List 转字符串
第一种:使用谷歌Joiner方法
String result = Joiner.on(",").join(list);
第二种:stream流
String result = list.stream().map(String::valueOf).collect(Collectors.joining(","));