我为多个集合的统一以下功能(包括重复的元素)多个集合的路口:Java中使用流+ lambda表达式
public static <T> List<T> unify(Collection<T>... collections) {
return Arrays.stream(collections)
.flatMap(Collection::stream)
.collect(Collectors.toList());
}
这将是很好有一个函数与一个类似的签名交集(使用类型相等)。例如:
public static <T> List<T> intersect(Collection<T>... collections) {
//Here is where the magic happens
}
我发现交叉功能的实现,但它不使用流:
public static <T> Set<T> intersect(Collection<? extends Collection<T>> collections) {
Set<T> common = new LinkedHashSet<T>();
if (!collections.isEmpty()) {
Iterator<? extends Collection<T>> iterator = collections.iterator();
common.addAll(iterator.next());
while (iterator.hasNext()) {
common.retainAll(iterator.next());
}
}
return common;
}
有什么办法来实现类似功能的统一利用流的东西吗?我在java8/stream api中没有那么经验,因为有些建议会非常有用。
为什么你认为你需要流? –
仅仅是好奇心!我同意提及,我真的是新的Java 8 /流API,所以我目前正试图学习更多的使用api :) –
正确。就我个人而言,我觉得学习这些API的最好方法就是尝试自己解决这样的问题。试试看,如果您遇到困难,请回来一个**特定**问题,概述您的问题。 –