Stream流

Stream的创建

//第 一种 实现或继承 Collection接口的集合 
// 如list.set 直接调用 stream() 方法
List<Integer> ids = Arrays.asList(10, 20, 30, 40, 50);
ids.stream();
Set<String> sets = new HashSet<>();
sets.stream();
// 数组使用 Arrays.stream(array) 转未Stream流
Integer[] array = new Integer[]{1, 5, 5, 8, 6, 7, 9, 5};
Stream<Integer> stream = Arrays.stream(array);

//Stream.of()
Integer min = Stream
		.of(1, 2, 3)
		//获取 最小值
        .min(Comparator.comparingInt(x -> x))
        .get();
System.out.println(min); //1

Integer max = Stream
       .of(1, 2, 3)
       //获取 最大值
       .max(Comparator.comparingInt(x -> x))
       .get();
System.out.println(max); //3

例子

从给定句子 中返回单词长度大于 5 的单词列表,按长度倒序输出,最多返回 3 个

//长度大于5 ,按长度倒序排序,输出 单词,最多3个
public static void lenMoreThan5SortConTop3sentence(String sentence) {
    String[] sentences = sentence.split(" ");
    List<String> word = Arrays.stream(sentences)
            .filter(x -> x.length() > 5)
            .sorted((o1, o2) -> o2.length() - o1.length())
            .limit(3)
            .collect(Collectors.toList());


}

管道

开始管道
在这里插入图片描述

中间管道
在这里插入图片描述
终止管道
在这里插入图片描述在这里插入图片描述

Map与flatMap

有一个字符串 ID 列表,现在 需要将其转为 User 对象列表。

public void stringToIntMap() {
    List<String> ids =
            Arrays.asList("205", "105", "308", "469", "627", "193", "111");
    // 使用流操作
    List<User> results = ids.stream()
            .map(id -> {
                User user = new User();
                user.setId(id);
                return user;
            })
            .collect(Collectors.toList());
    System.out.println(results);
}

现有一个句子列表,需要 将句子中每个单词都提取出来得到一个所有单词列表

public static void stringToIntFlatmap() {
    List<String> sentences = Arrays.asList("hello world", "Jia Gou Wu Dao");
    // 使用流操作
    List<String> results = sentences.stream()
            // 将 其中的每个元素转为新的流操作
            // 最后合并
            .flatMap(sentence -> Arrays.stream(sentence.split(" ")))
            .collect(Collectors.toList());
    System.out.println(results);
}

将两个字符数组合并成一个新的字符数组

public static void stringToIntFlatmap() {
    List<String> list = Arrays.asList("m,k,l,a", "1,3,5,7");

    List<String> listNew = list.stream().flatMap(x -> {
        String[] split = x.split(",");
        return Arrays.stream(split);
    }).collect(Collectors.toList());

    System.out.println("处理前的集合:" + list);
    System.out.println("处理后的集合:" + listNew);
}

peek 和 foreach 方法

peek 在终止操作后执行 ,foreach 为终止方法

List<String> sentences = Arrays.asList("hello world", "Jia Gou Wu Dao");
// 演示点 1:仅 peek 操作,最终不会执行
System.out.println("----before peek----");
sentences.stream().peek(sentence ->
        System.out.println(sentence));
System.out.println("----after peek----");
// 演示点 2:仅 foreach 操作,最终会执行
System.out.println("----before foreach----");
sentences.stream().forEach(sentence ->
        System.out.println(sentence));
System.out.println("----after foreach----");
// 演示点 3:peek 操作后面增加终止操作,peek 会执行
System.out.println("----before peek and count----");
sentences.stream().peek(sentence ->
        System.out.println(sentence)).count();
System.out.println("----after peek and count----");

filter、sorted、distinct、limit、skip

List<String> ids =
         Arrays.asList("205", "10", "308", "49", "627", "193", "111", "193");
 // 使用流操作,
 List<String> stringList = ids.stream()
         //111 193 205 308 627
         .filter(s -> s.length() > 2)
         //去重
         .distinct()
         //重新映射
         .map(Integer::valueOf)
         //正排序
         .sorted((o1, o2) -> o1 - o2)
         //跳过前2个元素
         .skip(2)
         //最多显示三条
         .limit(3)
         //再映射
         .map(String::valueOf)
         //收集
         .collect(Collectors.toList());
 System.out.println(stringList);


max、min

Integer min = Stream
		.of(1, 2, 3)
		//获取 最小值
        .min(Comparator.comparingInt(x -> x))
        .get();
System.out.println(min);

Integer max = Stream
       .of(1, 2, 3)
       //获取 最大值
       .max(Comparator.comparingInt(x -> x))
       .get();
System.out.println(max);

count、toArray

List<String> ids =
        Arrays.asList("205", "10", "308", "49", "627", "193", "111", "193");
	long count = ids.stream()
	        .map(Integer::valueOf)
	        // 统计个数
	        .count();
	System.out.println(count);

Integer[] integers = ids.stream()
        .map(Integer::valueOf)
        // 需要 指定转成的数组类型!!
        .toArray(Integer[]::new);

结果收集方法collect

toList、toSet、toMap

List<String> ids =
        Arrays.asList("205", "10", "308", "49", "627", "193", "111", "193");
Stream<Integer> integerStream = ids.stream().map(Integer::valueOf);
List<Integer> list = integerStream.collect(Collectors.toList());
Set<Integer> set = integerStream.collect(Collectors.toSet());


ArrayList<Integer> ids = new ArrayList<> ();
Map<Integer, Integer> idMap = ids.stream ()
        // 第一个是拿什么作为 key
        // 第二个是拿什么作为 value
        .collect (Collectors.toMap (item -> item, item -> item));


averaging

在这里插入图片描述

List<String> ids =
        Arrays.asList("205", "10", "308", "49", "627", "193", "111", "193");
Double avg = ids.stream()
        .map(Integer::valueOf)
        .collect(Collectors.averagingInt(Integer::valueOf));
System.out.println(avg);
//-----------------------------------
List<String> ids =
        Arrays.asList("205", "10", "308", "49", "627", "193", "111", "193");
Long collect = ids.stream()
        .map(Integer::valueOf)
        .collect(Collectors.counting());
System.out.println(collect);
//-----------------------------------
List<String> ids =
        Arrays.asList("205", "10", "308", "49", "627", "193", "111", "193");
IntSummaryStatistics summaryStatistics = ids.stream()
        .map(Integer::valueOf)
        .collect(Collectors.summarizingInt(x -> x));
System.out.println(summaryStatistics.getMax());

joining拼接成 字符串

List<String> list = Arrays.asList("A", "B", "C");
String res = list.stream()
        .collect(
                Collectors.joining("---")
        );
System.out.println(res);

partitioningBy分区、groupingBy分组

partitioningBy 分区

List<String> list = Arrays.asList("200", "100", "120", "110", "154");
// 将 数值 是否大于 120 分区!!
// partitioningBy 参数类型为 Predicate,有参且 有个Boolean 返回值
Map<Boolean, List<Integer>> partitioningByMap = list.stream()
        .map(Integer::valueOf)
        .collect(
                Collectors.partitioningBy(x -> x > 120)
        );
for (Map.Entry<Boolean, List<Integer>> booleanListEntry : partitioningByMap.entrySet()) {
    System.out.println(booleanListEntry.getKey());
    System.out.println(booleanListEntry.getValue());
}

groupingBy 分组

// 将员工按性别分组
Map<String, List<Person>> group = list.stream().collect(Collectors.groupingBy(Person::getSex));
// 将员工先按性别分组,再按地区分组
Map<String, Map<String, List<Person>>> group2 = personList.stream()
        .collect(
                Collectors.groupingBy(
                        Person::getSex,
                        Collectors.groupingBy(Person::getArea))
        );

避坑提醒

一旦一个 Stream 被执行了终止操作之后,后续便不可以再读这个流

执行其他的操作了,否则会报错

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值