Java 8新特性——Stream的集合操作---真香

Java8新特性

Java 8 API添加了一个新的抽象称为流Stream,可以让你以一种声明的方式处理数据。
Stream 使用一种类似用 SQL 语句从数据库查询数据的直观方式来提供一种对 Java 集合运算和表达的高阶抽象。
Stream API可以极大提高Java程序员的生产力,让程序员写出高效率、干净、简洁的代码。
这种风格将要处理的元素集合看作一种流, 流在管道中传输, 并且可以在管道的节点上进行处理, 比如筛选, 排序,聚合等。
元素流在管道中经过中间操作(intermediate operation)的处理,最后由最终操作(terminal operation)得到前面处理的结果。

目录

  • 为什么要使用Stream
  • 实例数据源
  • 方法
    • filter
    • map
    • sorted
    • limit
    • forEach
    • collect

为什么使用Stream

  1. 函数式编程带来的好处尤为明显。这种代码更多地表达了业务逻辑的意图,而不是它的实现机制。易读的代码也易于维护、更可靠、更不容易出错。
  2. 高端,
    ##实例数据源
static ArrayList<people> peoples = new ArrayList<>();
    static {
        for (int i = 0; i < 100; i++) {
            peoples.add(new people("sjy" + i, i + 10));
            peoples.add(new people("sjy1" + i, i + 10));
        }
    }
    static class people {
        String name;
        int age;
        public int getAge() {
            return age;
        }
        public people(String name, int age) {
            this.name = name;
            this.age = age;
        }
        @Override
        public String toString() {
            return "people{" +
                    "name='" + name + '\'' +
                    ", age=" + age +
                    '}';
        }
    }

方法

Stream接口提供了很多方法,经常使用的有以下几种:迭代、条件过滤、将流转换成集合和聚合元素、获取指定数量的流等等

filter
filter() API给定的解释是:返回由与此给定谓词匹配的此流的元素组成的流。 方法用于通过设置的条件过滤出元素,其实就是条件过滤

条件:获取age大于等于100的用户信息

//filter是条件,参数使用Lambda表达式  
List<people> collect = peoples.stream().filter(people -> people.getAge() >= 100).collect(Collectors.toList());
System.out.println(collect.size()); // 输出结果为20

map

map 方法用于映射每个元素到对应的结果,看代码就可以理解
条件:获取所有的年龄,获取所有的用户

  //从代码可以看出getAge()方法的返回值是int类型,所以List<Integer>
  List<Integer> collect = peoples.stream().map(people -> {
          return   people.getAge();
        }).collect(Collectors.toList());
        System.out.println(collect);
  //从代码可以看出toString()方法的返回值是String类型,所以List<String>
  List<String> collect1 = peoples.stream().map(people::toString).collect(Collectors.toList());
        System.out.println(collect1);

sorted
sorted 方法用于对流进行排序
其实使用peoples.stream().forEach(System.out::println)遍历出的顺序跟添加时候的是不一样的,
stream() − 为集合创建串行流。
parallelStream() − 为集合创建并行流。
条件:按照年龄的顺序排序

	System.out.println(peoples);
List<people> collect = peoples.stream().sorted(Comparator.comparingInt(people::getAge)).collect(Collectors.toList());
	System.out.println(collect);
List<people> collect2 = peoples.stream().sorted((o1, o2) -> o2.getAge()-o1.getAge()).collect(Collectors.toList());
	System.out.println(collect2);

limit
limit 方法用于获取指定数量的流

	List<people> collect = peoples.stream().limit(3).collect(Collectors.toList());
 	System.out.println(collect.size());//输出结果 3

forEach

		peoples.stream().forEach(people -> System.out.println(people.toString()));

collect

可以发现所有的方法后面都跟着这个collect方法。该方法的条件是Collector类,
Collectors 类实现了很多归约操作,例如将流转换成集合和聚合元素。Collectors 可用于返回列表或字符串:
其实就是执行map检索的元素的流转化成相应的数据格式,如Set List Map等

		Set<Integer> collect = peoples.stream().map(people::getAge).collect(Collectors.toSet());
        System.out.println(collect.size());
        List<Integer> collect1 = peoples.stream().map(people::getAge).collect(Collectors.toList());

        System.out.println(collect1.size());

添加一个分组的方法

条件:根据相同的年龄进行分组
大家知道对list泛型的某个属性进行分组的时候仅仅一行代码是不能完成的,就写出Java1.7之前的方法了,直接使用Java1.8中的新特性,是不是真香·······

		Map<Integer, List<people>> collect = peoples.stream().collect(Collectors.groupingBy(people::getAge));
        System.out.println(collect.size());

如果使用过MyBatis-plus的知道,这个跟MyBatis中的构造器很像,我们直接加一系列的条件,获得自己想要的结果。

public class Stream_Demo {
    static ArrayList<people> peoples = new ArrayList<>();
    static {
        for (int i = 0; i < 100; i++) {
            peoples.add(new people("sjy" + i, i + 10));
            peoples.add(new people("sjy1" + i, i + 10));
        }
    }
    static class people {
        String name;
        int age;
        public int getAge() {
            return age;
        }
        public people(String name, int age) {
            this.name = name;
            this.age = age;
        }
        @Override
        public String toString() {
            return "people{" +
                    "name='" + name + '\'' +
                    ", age=" + age +
                    '}';
        }
    }
    public static void main(String[] args){
        //filter是条件,参数使用Lambda表达式
        /*List<people> collect = peoples.stream().filter(people -> people.getAge() >= 100).collect(Collectors.toList());
        System.out.println(collect.size());*/
        /*List<Integer> collect = peoples.stream().map(people -> {
          return   people.getAge();
        }).collect(Collectors.toList());
        System.out.println(collect);

        List<String> collect1 = peoples.stream().map(people::toString).collect(Collectors.toList());
        System.out.println(collect1);*/

        /*System.out.println(peoples);
        List<people> collect = peoples.stream().sorted(Comparator.comparingInt(people::getAge)).collect(Collectors.toList());
        System.out.println(collect);
        List<people> collect2 = peoples.stream().sorted((o1, o2) -> o2.getAge()-o1.getAge()).collect(Collectors.toList());
        System.out.println(collect2);*/

        /*List<people> collect = peoples.stream().limit(3).collect(Collectors.toList());
       // System.out.println(collect.size());
        long end,start;
        peoples.stream().forEach(people::toString);*/

        /*Set<Integer> collect = peoples.stream().map(people::getAge).collect(Collectors.toSet());
        System.out.println(collect.size());
        List<Integer> collect1 = peoples.stream().map(people::getAge).collect(Collectors.toList());

        System.out.println(collect1.size());*/

        Map<Integer, List<people>> collect = peoples.stream().collect(Collectors.groupingBy(people::getAge));
        System.out.println(collect.size());
    }
}

2020.08.17

 List<Integer> list1=new ArrayList<>();
        list1.add(1);
        list1.add(2);
        list1.add(3);

        List<Integer> list2=new ArrayList<>();
        list2.add(3);
        list2.add(4);
        list2.add(5);

        System.out.println("====求交集===");

        List<Integer> list=list1.stream().filter(t->list2.contains(t)).collect(Collectors.toList());
        list.stream().forEach(System.out::println);




        System.out.println("====求差集===");
        list=list1.stream().filter(t-> !list2.contains(t)).collect(Collectors.toList());
        list.stream().forEach(System.out::println);


        System.out.println("====求并集===");

        list.addAll(list1);
        list.addAll(list2);
        list=list.stream().distinct().collect(Collectors.toList());
        list.stream().forEach(System.out::println);
获取字段是否都一样,
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值