Java 8 Stream 如何还原为集合

由于 Java 对集合的函数式操作并非原生态的,必须对得到的 stream() 进行过滤等操作,之后还是一个
stream(),一般我们最后返回给调用者需还原为相应的集合。这无法与 Scala 的 for … yield 操作相比。例如下面在使用
Stream API 过滤获得所有大于 3 的数字之后,方法的返回值还应该还原为 List, 这个需求非常自然

List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);
List<Integer> greaterThan3(list) {
  Stream<Integer> streamOfInteger = list.stream().filter( i -> i > 3);
  return streamOfInteger.ToIntegerList......;
}

我们这儿的问题就是如何把上面的 streamOfInteger 转换为 List, 有以下几种办法

  • 1 使用 Collectors.toList 方法 ***

    streamOfInteger.collect(Collectors.toList());

  • 2 使用 toCollection() 方法 **

    streamOfInteger.collect(Collectors.toCollection(ArrayList::new))

  • 3 forEach() 方法 *

    List newList = new ArrayList<>();
    streamOfInteger.forEach(newList::add);
    streamOfInteger.forEachOrdered(newList::add); //或者

  • 4 toArray() 方法

    Integer[] arrayOfInteger = streamOfInteger.toArray(Integer[]::new);
    List newList = Arrays.asList(arrayOfInteger);

此法更觉多此一举 此外,不妨窥探下使用 Stream API 处理后的 Map 该如何还原为 Map

Map<String, String> map = new HashMap<>();
map.put("a", "aa");
map.put("b", "bb");
Stream<Map.Entry<String, String>> filtered = map.entrySet().stream()
  .filter(entry -> entry.getKey().equals("b"));

filtered.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
    
//或
filtered.collect(Collectors.toMap(entry -> entry.getKey(), entry -> entry.getValue()));
    
//或
Map<String, String> newMap = new HashMap<>();
filtered.forEach(entry -> newMap.put(entry.getKey(), entry.getValue()));

无意中发现了一个巨牛的人工智能教程,忍不住分享一下给大家。教程不仅是零基础,通俗易懂,而且非常风趣幽默,像看小说一样!觉得太牛了,所以分享给大家。点这里可以跳转到教程。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值