实体类:student
@Data
@EqualsAndHashCode
@AllArgsConstructor
public class Student {
private Integer id;
private String name;
private String classes;
private Integer age;
}
// 模拟数据
List<Student> list1 = new ArrayList<>();
list1.add(new Student(1, "zhangsan", "一班", 18));
list1.add(new Student(2, "lisi", "二班", 20));
List<Student> list2 = new ArrayList<>();
list2.add(new Student(4, "zhangsan", "一班", 18));
一:在姓名,班级相同的条件下,相加年龄,将数据合并
// 合并
List<Student> students = new ArrayList<>();
Stream.concat(list1.stream(), list2.stream())
.collect(
Collectors.groupingBy(item -> (item.getName() + item.getClasses()),
Collectors.toList())
).forEach(
(key, value) -> {
value.stream().reduce(
(a, b) -> new Student(a.getId(), a.getName(), a.getClasses(), a.getAge() + b.getAge())
).ifPresent(students::add);
}
);
System.out.println("list1与list2合并:"+students);
二:使用BigDecimal求List的总数
double sum =doubleList.stream()
.map(BigDecimal::valueOf)
.reduce(BigDecimal.ZERO, BigDecimal::add)
.doubleValue();
三:使用BigDecimal求List<Map<String,Double>>的总数
Map<String, Double> dataTotal = returnList.stream()
.flatMap(o -> o.entrySet().stream())
.filter(entry -> entry.getValue() instanceof Double)
.collect(Collectors.groupingBy(
Map.Entry::getKey,
//Collectors.summingDouble(entry -> (double) entry.getValue())
Collectors.reducing(BigDecimal.ZERO, entry -> BigDecimal.valueOf((Double) entry.getValue()), BigDecimal::add)
)).entrySet().stream()
.collect(Collectors.toMap(
Map.Entry::getKey,
entry->entry.getValue().doubleValue()
));
四:判断实体某字段值个数
Map<String, Long> barCodeCollect = commodityList.stream()
.collect(Collectors.groupingBy(CommodityVO::getBarCode, Collectors.counting()));
if (barCodeCollect.values().stream()
.anyMatch(count -> count > 1)) {
return AjaxResult.error("商品重复!");
}