Stream的基本操作
public static void main(String[] args) {
List<Apple> collect = appleStore.stream().filter(a -> a.getWeight() > 100).collect(Collectors.toList());
Map<Integer, String> collect1 = appleStore.stream().collect(Collectors.toMap(Apple::getId, Apple::getColor, (a, b) -> b));
Map<Integer, Apple> collect2 = appleStore.stream().collect(Collectors.toMap(Apple::getId, apple -> apple, (a, b) -> b));
Integer sum = appleStore.stream().collect(reducing(2000, Apple::getWeight, (a, b) -> a - b));
Map<String, List<Apple>> collect3 = appleStore.stream().collect(groupingBy(Apple::getBirthplace));
Map<String, Long> collect3 = appleStore.stream().collect(groupingBy(Apple::getBirthplace, Collectors.counting()));
Map<Long, List<Long>> collect2 = fetch1.stream().collect(groupingBy(EventOrgEntity::getRuleId, Collectors.mapping(EventOrgEntity::getOrgId, Collectors.toList())));
Integer collect4 = appleStore.stream().collect(summingInt(Apple::getWeight));
Double collect5 = appleStore.stream().collect(averagingInt(Apple::getWeight));
System.out.println(collect5);
List<Person> distinctElements = list.stream()
.filter( distinctByKey(p -> p.getId()) )
.collect( Collectors.toList() );
public static <T> Predicate<T> distinctByKey(Function<? super T, Object> keyExtractor){
Map<Object, Boolean> map = new ConcurrentHashMap<>();
return t -> map.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;
}
规约操作 求集合中一个字段的和
BigDecimal memberOrder = orders.stream().filter(order -> PointTypeEnum.MEMBER.getCode().equals(order.getPointType())).map(OrderDO::getPointAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
获取List中List内的一个字段
List<String> collect = byAgentCodeAndDeliveryStatus.parallelStream().map(d -> d.getDeliveryOrderProductDOS().stream().map(DeliveryOrderProductDO::getSkuId).collect(Collectors.toList())).flatMap(List::stream).collect(Collectors.toList());
List<RebateProductRulesDO> rebateProductRulesDOS = rebateRulesDOS.stream().map(RebateRulesDO::getRebateProductRules).collect(Collectors.toList()).stream().flatMap(Collection::stream).collect(Collectors.toList());
获取集合中某个字段的最小值
User minAgeUser = users.stream().min(Comparator.comparing(User::getAge)).get();
@Data
public class Apple {
private int id;
private String color;
private int weight;
private String birthplace;
public Apple(int id, String color, int weight, String birthplace) {
this.id = id;
this.color = color;
this.weight = weight;
this.birthplace = birthplace;
}
}
private static final List<Apple> appleStore = Arrays.asList(
new Apple(1, "red", 500, "湖南"),
new Apple(2, "red", 100, "天津"),
new Apple(2, "red", 100, "天津"),
new Apple(3, "green", 300, "湖南"),
new Apple(4, "green", 200, "天津"),
new Apple(5, "green", 100, "湖南")
);