java 8 学习笔记 流 collect map filter flatMap max 和min

1.

collect(toList()) 方法由Stream 里的值生成一个列表,是一个及早求值操作。

List<String> collected = Stream.of("a", "b", "c")
        .collect(Collectors.toList());

collected.forEach(System.out::println);

2.

map 操作就可以使用该函数,将一个流中的值转换成一个新的流

List<String> collected = Stream.of("a", "b", "hello")
        .map(string -> string.toUpperCase())➊
                       .collect(Collectors.toList());

collected.forEach(System.out::println);

传给map ➊的Lambda表达式只接受一个String 类型的参数,返回一个新的String 。参数和返回值不必属于同一种类型,但是Lambda表达式必须是Function 接口的一个实例,Function 接口是只包含一个参数的普通函数接口。

 

3.

遍历数据并检查其中的元素时,可尝试使用Stream 中提供的新方法filter .

List<String> stringArrayList =
        asList("1q234","1q342","1q2334","1q434","q34","324","q3224","22q34","22q34");

System.out.println("含有q的有:" + String.valueOf(stringArrayList.stream()
        .filter(string -> {
            System.out.println(string);
            return string.contains("q");
        })
        .count()) + "个");

4.

flatMap 方法可用Stream 替换值,然后将多个Stream连接成一个Stream

List<Integer> together = Stream.of(asList(1, 2), asList(3, 4))
        .flatMap(Collection::stream)
        .collect(toList());

together.forEach(System.out::println);

5.

maxmin

List<String> stringList = asList("1", "22", "333", "4444", "55555");
String s = stringList.stream()
        .min(Comparator.comparing(string -> string.length()))
        .get();
System.out.println("-------min-----");
System.out.println(s);

List<String> stringList = asList("1", "22", "333", "4444", "55555");
String s = stringList.stream()
        .max(Comparator.comparing(string -> string.length()))
        .get();
System.out.println("-------max-----");
System.out.println(s);

 

 

 

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值