@Test
public void ListObject() throws Exception {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-dd-MM");
List<Area> areaList = new ArrayList<>();
Area a1 = new Area(1, 10L, "河南", new BigDecimal(100), 1);
Area a2 = new Area(2, 20L, "江西", new BigDecimal(200), 2);
Area a3 = new Area(3, 30L, "北京", new BigDecimal(300), 3);
Area a4 = new Area(4, 40L, "天津", new BigDecimal(400), 1);
areaList.add(a4);
areaList.add(a1);
areaList.add(a2);
areaList.add(a3);
// 集合对象某一个字段抽取出来排成集合
List<Integer> fieldList = areaList.stream().map(item -> item.getId()).collect(toList());
System.out.println("集合对象某一个字段抽取出来排成集合 = " + fieldList);
// 集合对象某一个字段抽取出来排成字符串
String listObjToStr = areaList.stream().map(item -> String.valueOf(item.getId())).collect(joining(","));
System.out.println("集合对象某一个字段抽取出来排成字符串 = " + listObjToStr);
// 集合对象某一个字段抽取出来排成String数组
String[] listObjToStrArray = areaList.stream().map(item -> String.valueOf(item.getId())).toArray(String[]::new);
System.out.println("集合对象某一个字段抽取出来排成String数组 = " + listObjToStrArray);
// 集合对象某一个字段抽取出来排成Long数组
Long[] longs = areaList.stream().map(item -> item.getUid()).toArray(Long[]::new);
System.out.println("集合对象某一个字段抽取出来排成Long数组 = " + longs);
// 集合对象某一个字段抽取出来排成Integer数组
Integer[] integers = areaList.stream().map(item -> item.getId()).toArray(Integer[]::new);
System.out.println("集合对象某一个字段抽取出来排成Integer数组 = " + integers);
// 集合中对象去重
List<Area> uniqueList = areaList.stream().collect(collectingAndThen(toCollection(() -> new TreeSet<>(comparingLong(Area::getLevel))), ArrayList::new));
System.out.println("集合中对象去重 = " + uniqueList);
// 集合对象单个条件虑重
List<Area> uniqueList2 = areaList.stream().collect(collectingAndThen(toCollection(() -> new TreeSet<>(Comparator.comparing(Area::getName))), ArrayList::new));
System.out.println("集合中对象去重 = " + uniqueList2);
// 集合中对象多个条件去重
List<Area> uniqueList3 = areaList.stream().collect(collectingAndThen(toCollection(() -> new TreeSet<>(Comparator.comparing(item -> item.getName() + item.getId()))), ArrayList::new));
System.out.println("集合中对象去重 = " + uniqueList3);
// 将一个集合数据赋值带新的集合
List<AreaVO> newList = areaList.stream().map(sg -> {
AreaVO areaVO = CglibUtil.copyPropertes(sg, AreaVO.class);
return areaVO;
}).collect(toList());
System.out.println("将一个集合数据赋值带新的集合 = " + newList);
//过滤排序出符合条件的数据
Integer value = 10;
List<Area> filterList = areaList.stream()
.filter(item -> item.getUid().equals(Long.valueOf(value)))
.filter(item -> item.getLevel() >= 2)
.sorted(Comparator.comparing(Area::getId))//依id升序排序
.sorted(Comparator.comparing(Area::getId).reversed())//依id降序排序
.collect(toList());
System.out.println("过滤出符合条件的数据 = " + filterList);
// 计算求和数量 方式1
Integer integerTotalSum = areaList.stream().collect(summingInt(Area::getId));
System.out.println("计算数量integerTotalSum = " + integerTotalSum);
Double doubleTotalSum = areaList.stream().collect(summingDouble(Area::getId));
System.out.println("计算数量doubleTotalSum = " + doubleTotalSum);
Long longTotalSum = areaList.stream().collect(summingLong(Area::getId));
System.out.println("计算数量longTotalSum = " + longTotalSum);
// 计算求和数量 方式2
Integer intTotalSum = areaList.stream().map(Area::getId).reduce(Integer::sum).get();
System.out.println("计算求和数量asInteger = " + intTotalSum);
Long asLong = areaList.stream().mapToLong(Area::getId).reduce(Long::sum).getAsLong();
System.out.println("计算求和数量asLong = " + asLong);
Double asDouble = areaList.stream().mapToDouble(Area::getId).reduce(Double::sum).getAsDouble();
System.out.println("计算求和数量asDouble = " + asDouble);
// bigdecimal计算数量求和
BigDecimal totalMoney = areaList.stream().map(Area::getMoney).reduce(BigDecimal.ZERO, BigDecimal::add);
System.out.println("bigdecimal计算数量求和 = " + totalMoney);
// 求平均值
Double avgCalories = areaList.stream().collect(averagingInt(Area::getId));
System.out.println("求平均值 = " + avgCalories);
// 集合中对象某个字段最大值对象
Optional<Area> maxObj = areaList.stream().collect(maxBy(Comparator.comparing(Area::getId)));
System.out.println("集合中对象某个字段最大值对象 = " + maxObj);
// 集合中对象某个字段最小值对象
Optional<Area> minObj = areaList.stream().collect(minBy(Comparator.comparing(Area::getId)));
System.out.println("集合中对象某个字段最小值对象 = " + minObj);
// 统计某个值全部参数
IntSummaryStatistics summaryStatistics = areaList.stream().collect(summarizingInt(Area::getId));
System.out.println("统计某个值全部参数 = " + summaryStatistics);
// 集合对象是否符合某个条件标准
boolean isAllAdult = areaList.stream().allMatch(item -> item.getId() > 2);
System.out.println("集合对象是否符合某个条件标准 = " + isAllAdult);
// 集合对象转Map
Map<Integer, Area> areaMap = areaList.stream().collect(toMap(Area::getId, Function.identity(),(existing, replacement) -> existing));
System.out.println("集合对象转Map = " + areaMap);
// (k1,k2)->k1 来设置,如果有重复的key,则保留key1,舍弃key2(后者数据)
Map<Integer, Area> listToMap = areaList.stream().collect(toMap(e -> e.getLevel(), item -> item, (k1, k2) -> k1));
Map<Integer, Area> listToLinkedHashMap = areaList.stream().collect(toMap(e -> e.getLevel(), Function.identity(), (k1, k2) -> k1, LinkedHashMap::new));
System.out.println("根据ID,List转Map = " + listToMap);
System.out.println("根据ID,List转Map = " + listToLinkedHashMap);
//List 以level分组转化成map
Map<Integer, List<Area>> mapByGroup = areaList.stream().collect(groupingBy(Area::getLevel));
System.out.println("List以level分组转化成map = " + mapByGroup);
//List以level分组,求和id值
Map<Integer, Integer> listGroupFiledSum = areaList.stream().collect(groupingBy(Area::getLevel, summingInt(Area::getId)));
System.out.println("List以level分组,求和id值 = " + listGroupFiledSum);
//单个字段,分组求和(datas)获取到sum,max,min,count
Map<Integer, LongSummaryStatistics> enusersCollect = areaList.stream().collect(groupingBy(Area::getLevel, summarizingLong(Area::getUid)));
System.out.println("enusersCollect = " + enusersCollect);
//多个字段,分组求和(先按level分组,再按uid分组,求和id)
Map<Integer, Map<Long, IntSummaryStatistics>> integerMapMap = areaList.stream().collect(groupingBy(Area::getLevel, groupingBy(Area::getUid, summarizingInt(Area::getId))));
System.out.println("integerMapMap = " + integerMapMap);
//List以level分组,求和money值
Map<Integer, BigDecimal> groupFiledBigDecimalSum = areaList.stream().collect(groupingBy(Area::getLevel, CollectorsUtil.summingBigDecimal(Area::getMoney)));
System.out.println("groupFiledBigDecimalSum = " + groupFiledBigDecimalSum);
// list以level分组,然后求每组level的最大值
Map<Integer, Optional<Area>> listGroupMaxObj = areaList.stream().collect(groupingBy(Area::getLevel, maxBy(comparingInt(Area::getLevel))));
System.out.println("list以level分组,然后求每组level的最大值 = " + listGroupMaxObj);
// list以level分组,然后求每组level的最小值
Map<Integer, Optional<Area>> listGroupMinObj = areaList.stream().collect(groupingBy(Area::getLevel, minBy(comparingInt(Area::getLevel))));
System.out.println("list以level分组,然后求每组level的最大值 = " + listGroupMinObj);
}
package com.camelot.sysbase.common.JavaUtils;
import java.math.BigDecimal;
import java.util.Collections;
import java.util.Set;
import java.util.function.BiConsumer;
import java.util.function.BinaryOperator;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collector;
public class CollectorsUtil {
static final Set<Collector.Characteristics> CH_NOID = Collections.emptySet();
private CollectorsUtil() {
}
@SuppressWarnings("unchecked")
private static <I, R> Function<I, R> castingIdentity() {
return i -> (R) i;
}
/**
* Simple implementation class for {@code Collector}.
*
* @param <T> the type of elements to be collected
* @param <R> the type of the result
*/
static class CollectorImpl<T, A, R> implements Collector<T, A, R> {
private final Supplier<A> supplier;
private final BiConsumer<A, T> accumulator;
private final BinaryOperator<A> combiner;
private final Function<A, R> finisher;
private final Set<Characteristics> characteristics;
CollectorImpl(Supplier<A> supplier, BiConsumer<A, T> accumulator, BinaryOperator<A> combiner,
Function<A, R> finisher, Set<Characteristics> characteristics) {
this.supplier = supplier;
this.accumulator = accumulator;
this.combiner = combiner;
this.finisher = finisher;
this.characteristics = characteristics;
}
CollectorImpl(Supplier<A> supplier, BiConsumer<A, T> accumulator, BinaryOperator<A> combiner,
Set<Characteristics> characteristics) {
this(supplier, accumulator, combiner, castingIdentity(), characteristics);
}
@Override
public BiConsumer<A, T> accumulator() {
return accumulator;
}
@Override
public Supplier<A> supplier() {
return supplier;
}
@Override
public BinaryOperator<A> combiner() {
return combiner;
}
@Override
public Function<A, R> finisher() {
return finisher;
}
@Override
public Set<Characteristics> characteristics() {
return characteristics;
}
}
public static <T> Collector<T, ?, BigDecimal> summingBigDecimal(ToBigDecimalFunction<? super T> mapper) {
return new CollectorImpl<>(() -> new BigDecimal[1], (a, t) -> {
if (a[0] == null) {
a[0] = BigDecimal.ZERO;
}
a[0] = a[0].add(mapper.applyAsBigDecimal(t));
}, (a, b) -> {
a[0] = a[0].add(b[0]);
return a;
}, a -> a[0], CH_NOID);
}
}
package com.camelot.sysbase.common.JavaUtils;
import java.math.BigDecimal;
@FunctionalInterface
public interface ToBigDecimalFunction<T> {
BigDecimal applyAsBigDecimal(T value);
}