java8流式操作

简介:Stream 中文称为 “流”,通过将集合转换为这么一种叫做 “流” 的元素序列,通过声明性方式,能够对集合中的每个元素进行一系列并行或串行的流水线操作。

操作分类:

.stream()
stream()把一个源数据,可以是集合,数组,I/O channel, 产生器generator 等,转化成流

常见流操作API

中间操作

.filter()
filter()方法用于通过设置的条件过滤出元素
.map()
map()用于映射每个元素到对应的结果
.sorted()
sorted()用于对流进行排序
distinct():去除重复的元素

終端操作:

forEach():遍历每个元素。
findFirst()
findFirst()用于找到第一次出现的元素
reduce():把Stream 元素组合起来。例如,字符串拼接,数值的 sum,min,max ,average 都是特殊的 reduce。
collect():返回一个新的数据结构,基于Collectors有丰富的处理方法。Collectors类实现了很多归约操作,例如将流转换成集合和聚合元素。Collectors 可用于返回列表或字符串,collect()内可以用collectors进行转换:
min():找到最小值。
max():找到最大值。

中间操作:中间操作包括去重、过滤、映射等操作,值得说明的是,如果没有为流定义终端操作,为了避免无谓的计算,中间操作也不会执行

终端操作:终端产生最终的执行结果,并中断流式编程的衔接链,因此结束操作是最后一个操作

.collect(Collectors.toList());//列表
.collect(Collectors.joining(", "));//字符串

.isPresent()
isPresent()可以判断所找到的值是否是null

.orElse()
orElse(null)表示如果一个都没找到返回null

orElse()中可以塞默认值。如果找不到就会返回orElse中你自己设置的默认值。

补充:

Optional<T> findFirst() 
findFirst方法返回Optional包含流中第一个元素的元素,如果findFirst选择的元素为null,它将抛出NullPointerException

所以推荐将findFirst与orElse连用规避空指针的问题,如下所示:

A a = AList.stream().filter(a -> "小明".equals(a.getUserName())) .findFirst().orElse(null);


举例

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class StreamOperation {
    public static void main(String[] args) {
        List<StudentVO> list = initList();
        testFilter(list);

    }

    private static List<StudentVO> initList(){
        List<StudentVO> list = new ArrayList<>();
        StudentVO student1 = new StudentVO();
        student1.setKey("a");
        student1.setValue("str-a");
        student1.setName("李四");
        student1.setSex("男");
        list.add(student1);
        StudentVO student2 = new StudentVO();
        student2.setKey("b");
        student2.setValue("str-b");
        student1.setName("张三");
        student1.setSex("女");
        list.add(student2);
        StudentVO student3 = new StudentVO();
        student3.setKey("c");
        student3.setValue("str-c");
        student1.setName("小红");
        student1.setSex("女");
        list.add(student3);
        return list;
    }
    private static void testFilter(List<StudentVO> list){
        List<StudentVO> listNew = list.stream().filter(item->item.getKey().equals("a")).collect(Collectors.toList());
        listNew.forEach(studentVO->{
            System.out.println(studentVO.getKey());
            System.out.println(studentVO.getValue());
        });

        List<StudentVO> bList = list.stream().filter(item->item.getKey().equals("b")).collect(Collectors.toList());
        bList.forEach(studentVO->{
            System.out.println(studentVO.getKey());
            System.out.println(studentVO.getValue());
        });
    }

}

1,filter 

2,map

3, sorted排序

private static void testSorted(List<DemoVO> list){
    //自然排序,先对key进行排序,再对value进行排序。
    List<DemoVO> collect = list.stream().sorted(Comparator.comparing(DemoVO::getKey).thenComparing(DemoVO::getValue)).collect(Collectors.toList());
    System.out.println(JSON.toJSONString(collect));
    collect = list.stream().sorted(Comparator.comparing(DemoVO::getKey).thenComparing(DemoVO::getValue)).collect(Collectors.toList());
    System.out.println(JSON.toJSONString(collect));
}
 

输出结果:
[{"key":"a","value":"str-a"},{"key":"b","value":"str-b"},{"key":"c","value":"str-c"}]

4,去重

  //去重
    private static void testDistinct(List<StudentVO> list){
        List<StudentVO> collect = list.stream().distinct().collect(Collectors.toList());
        System.out.println(JSON.toJSONString(collect));
    }


//输出结果
[{"key":"a","value":"str-a"},{"key":"b","value":"str-b"},{"key":"c","value":"str-c"}]

5.List<Object>转List<attribute>


private static void convertToList(List<DemoVO> list){
    List<String> collect = list.stream().map(DemoVO::getValue).collect(Collectors.toList());
    System.out.println(JSON.toJSONString(collect));
}
 
 
 
//输出结果
["str-a","str-b","str-c"]

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值