Java基础:stream的基本使用

现在有一个需求:

将list集合中姓张的元素过滤到一个新的集合,然后将过滤出来的姓张的元素中,再过滤出来长度为3的元素,存储到一个新的集合中。

List<String> list1 = new ArrayList<>();
list1.add("张老三");
list1.add("张小三");
list1.add("李四");
list1.add("赵五");
list1.add("张六");
list1.add("王八");
        // 常规
        ArrayList<String> list2 = new ArrayList<>();
        // 1.将list集合中姓张的元素过滤到一个新的集合中
        for(String name : list1){
            if(name.startsWith("张")){
                list2.add(name);
            }
        }
        ArrayList list3 = new ArrayList();
        for (String name : list2) {
            if (name.length() == 3){
                list3.add(name);
            }
        }
// stream
list1.stream()
    .filter((String name)->name.startsWith("张"))
    .filter((String name)->name.length()==3)
    .forEach((String name)->{
    	System.out.println("符合条件的姓名:" + name);
    }
);

过滤器筛选,去重和获取第一个元素

public class Demo2 {
    public static void main (String[] args) {
        // 流的筛选
        List<Integer> integerList = Arrays.asList(1,2,3,3,4,5,6);
        // 筛选出集合中数字大于4的元素
        List<Integer> collect = integerList.stream().filter(x -> x > 4).collect(Collectors.toList());
        System.out.println(collect); // [5, 6]
        // 集合中的去重
        List<Integer> collect1 = integerList.stream().distinct().collect(Collectors.toList());
        System.out.println(collect1);// [1, 2, 3, 4, 5, 6]
        // 获取流中的第一个元素
        Optional<Integer> first = integerList.stream().filter(x -> x > 4).findFirst();
        Optional<Integer> any = integerList.stream().filter(x -> x > 4).findAny();
        Optional<Integer> any1 = integerList.parallelStream().filter(x -> x > 4).findAny();
        System.out.println(first); // Optional[5]
        System.out.println(any); //Optional[5]
        System.out.println(any1); // 预期结果不稳定

        if (first.isPresent()) {
            first.get(); // 返回Integer类型5
        }
    }
}

获取最长/短字符串,获取最大/小值,集合泛型最值和元素数量

class Demo3 {
    public static void main(String[] args) {
        List<String> stringList = Arrays.asList("huainvhai", "xiaotiancai", "bennvhai");
        // 获取集合中最长的字符串
        Optional<String> maxString = stringList.stream().max(Comparator.comparing(String::length));
        // 获取集合中最短字符串
        Optional<String> minString = stringList.stream().min(Comparator.comparing(String::length));
        System.out.println(maxString);
        System.out.println(minString);

        // 获取集合中的最大值
        List<Integer> integerList = Arrays.asList(1, 2, 3);
        Optional<Integer> maxInteger = integerList.stream().max((i, j) -> {
            return i - j;
        });
        // 获取集合中的最小值
        Optional<Integer> minInteger = integerList.stream().max((i, j) -> {
            return j - i;
        });
        System.out.println(maxInteger);
        System.out.println(minInteger);

        // 集合泛型是个对象的最值
        ArrayList<Person> personList = new ArrayList<>();
        personList.add(new Person("xiao",12));
        personList.add(new Person("xiao",20));
        personList.add(new Person("xiao",18));
        Optional<Person> max = personList.stream().max(Comparator.comparing(Person::getScore));
        
        // 获取集合中的元素数量
        long count = personList.stream().filter(p -> p.getScore() > 12).count();
        System.out.println(max);
        System.out.println(count);
    }
}

class Person{
    private String name;
    private Integer score;

    public Person(String name, Integer score) {
        this.name = name;
        this.score = score;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getScore() {
        return score;
    }
}

获取字段平均值,汇总某字段并转换成String,按照字段一级二级分组,转换成其它集合类型

class Demo5 {
    public static void main(String[] args) {
        ArrayList<Person> personList = new ArrayList<>();
        personList.add(new Person("nst1",12));
        personList.add(new Person("nst2",20));
        personList.add(new Person("nst3",18));
        personList.add(new Person("nst3",18));
        personList.add(new Person("nst3",28));

        //获取平均年龄averaging
        Double collect = personList.stream().collect(Collectors.averagingInt(Person::getScore));
        System.out.println(collect); //16.666666666666668

        //最大/小,平均和求和汇总方法
        DoubleSummaryStatistics collect1 = personList.stream()
                .collect(Collectors.summarizingDouble(Person::getScore));
        System.out.println(collect1); // DoubleSummaryStatistics{count=3, sum=50.000000, min=12.000000, average=16.666667, max=20.000000}

        //抽取某字段并转换成String
        String collect2 = personList.stream().map(p -> p.getName())
                .collect(Collectors.joining(","));
        System.out.println(collect2);  //nst1,nst2,nst3

        //groupingBy
        //以名字进行分组
        Map<String, List<Person>> collect4 = personList.stream()
                .collect(Collectors.groupingBy(Person::getName));
        System.out.println(collect4); //{xiao=[Person(name=xiao, age=12), Person(name=xiao, age=20), Person(name=xiao, age=18)]}

        //先以名字分组,再以年龄分组
        Map<String, Map<Integer, List<Person>>> collect5 = personList.stream()
                .collect(Collectors.groupingBy(Person::getName,
                        Collectors.groupingBy(Person::getScore)));
        System.out.println(collect5); //{xiao={18=[Person(name=xiao, age=18)], 20=[Person(name=xiao, age=20)], 12=[Person(name=xiao, age=12)]}}

        //toList、toSet、toMap
        Set<Person> collect6 = personList.stream().collect(Collectors.toSet());
        System.out.println(collect6);//[Person(name=xiao, age=18), Person(name=xiao, age=20), Person(name=xiao, age=12)]
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值