Java Stream操作技巧
  exXbQnf8Zl8L 2023年11月02日 43 0

Java Stream操作技巧

Strean是Java8的特性,串行处理数据,更高效;parallelStream是一种高级的流处理

一. Stream创建方式

描述 示例
Collection的stream()方法 Arrays.asList(1,2,3).stream()

二. 常见的流处理中间操作

1. map()

常规写法

List idcards=new ArrayList();
for(int i=0;i
  idcards.add(users.get(i).getIdcard());
}

使用map()

List idcards = users.stream().map(User::getIdcard).collect(Collectors.toList())

2. filter()

Collection<Person> collection = new ArrayList();
collection.add(new Person("张三", "男"));
collection.add(new Person("李四", "女"));
collection.add(new Person("王五", "男"));
collection.add(new Person("赵六", "男"));

Stream<Person> personStream = collection.stream().filter(new Predicate<Person>() {
    @Override
    public boolean test(Person person) {
        return "男".equals(person.getGender());//只保留男性
    }
});

collection = personStream.collect(Collectors.toList());//将Stream转化为List
System.out.println(collection.toString());//查看结果

3. limit()

List<Person> personList = Arrays.asList(
                new Person(1, "大毛", 30, 175),
                new Person(2, "二毛", 25, 170),
                new Person(3, "三毛", 25, 170),
                new Person(4, "小毛", 20, 163));
// 获取 Stream 流
Stream<Person> personStream = personList.stream();
// 截取前 2 个元素
personStream.limit(2).forEach(System.out::println);

4. skip()

Stream.of(1,2,3,4,5,6,7,8).skip(5).forEach(System.out::print);

5. distinct()

List<String> list = Arrays.asList("AA", "BB", "CC", "BB", "CC", "AA", "AA");
long l = list.stream().distinct().count();
System.out.println("No. of distinct elements:"+l);
String output = list.stream().distinct().collect(Collectors.joining(","));
System.out.println(output);

6. peek()

7. sorted()

三. 常见的流处理结束操作

1. collect()

2. forEach()

3. find()

4. reduce()

【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年11月08日 0

暂无评论

推荐阅读
  vxoexqgjyiCS   2023年11月19日   19   0   0 linuxSystemvim
  o3sdUNSaLXle   2023年11月02日   67   0   0 linuxsqlList
  Ebx3peZaz9BX   2023年11月02日   60   0   0 MemorySystemjava
  oIa1edJoFmXP   2023年11月22日   24   0   0 ide数据List
  vxoexqgjyiCS   2023年11月19日   20   0   0 linuxSystemvim
  9JCEeX0Eg8g4   2023年11月27日   31   0   0 DatabaseSystemmongodb