是否有一个Java Stream方法等同于Scala的集合“collect”? [英] Is there a Java Stream method equivalent to Scala's collections "collect"?

查看:481
本文介绍了是否有一个Java Stream方法等同于Scala的集合“collect”?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Scala的集合提供了一个名为 collect 的方法,它合并 filter map 进入单一方法。在过滤 Object 集合以生成仅包含特定类型的集合的子集时,它特别有用。

Scala's collection provides a method called collect that merges filter and map into a single method. It's particularly useful when filtering an Object collection to produce a subset of that collection containing only a particular type.

是Java 8的Stream有什么这样的东西吗?

Is there any such thing with Java 8's Stream?

推荐答案

组合过滤器 map 在给定类型系统的情况下,在Java中没有那么有用。例如。没有这样的 PartialFunction 类型。

Having a combination of filter and map in one step is not that useful in Java given its type system. E.g. there is no such PartialFunction type.

最接近的是 flatMap

List<Object> list=Arrays.asList(0, "foo", 0L, 42.0, true, "false");
List<String> sList = list.stream()
  .flatMap(o-> o instanceof String? Stream.of((String)o): Stream.empty())
  .collect(Collectors.toList());
System.out.println(sList);

但表现力

.flatMap(o-> o instanceof String? Stream.of((String)o): Stream.empty())

.filter(o -> o instanceof String).map(o -> (String)o)

当然,你可以创建一个帮助方法,将这些步骤封装在一个不可解析的操作中:

Of course, you may create a helper method encapsulating these steps in a single, undissolvable operation:

static <T> Stream<T> onlyType(Stream<?> s, Class<T> type) {
    return s.filter(type::isInstance).map(type::cast);
}

然后你就可以使用它了

List<String> sList=onlyType(list.stream(), String.class).collect(Collectors.toList());

这篇关于是否有一个Java Stream方法等同于Scala的集合“collect”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆