Stream的基本操作

95 阅读1分钟

本文已参与[新人创作礼]活动,一起开启掘金创作之路。

Stream的基本操作

    public static void main(String[] args) {
        //过滤条件
        List<Apple> collect = appleStore.stream().filter(a -> a.getWeight() > 100).collect(Collectors.toList());   //过滤条件
        //转成map类型,id为key值,color为vlue值
        Map<Integer, String> collect1 = appleStore.stream().collect(Collectors.toMap(Apple::getId, Apple::getColor, (a, b) -> b));     //转map
        //转成map类型,id为key值,apple为vlue值
        Map<Integer, Apple> collect2 = appleStore.stream().collect(Collectors.toMap(Apple::getId, apple -> apple, (a, b) -> b));
        //归约,总数减去累计weight值  统计
        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())));
        //求和 getWeight
        Integer collect4 = appleStore.stream().collect(summingInt(Apple::getWeight));
        //求平均值
        Double collect5 = appleStore.stream().collect(averagingInt(Apple::getWeight));
        System.out.println(collect5);
		//List去重
		List<Person> distinctElements = list.stream()
                                            .filter( distinctByKey(p -> p.getId()) )
                                            .collect( Collectors.toList() );
      	        //Utility function
     	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;
    	}

获取集合中某个字段的最小值

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, "湖南")
    );