我还没有找到任何现有的等价物,但下面的方法应该有效:
public static Stream join(
Stream outer,Stream inner,Function outerKeyFunc,Function innerKeyFunc,BiFunction resultFunc) {
//Collect the Inner values into a list as we'll need them repeatedly
List innerList = inner.collect(Collectors.toList());
//matches will store the matches between inner and outer
final Map> matches = new HashMap<>();
//results will be used to collect the results in
final List results = new ArrayList<>();
outer.forEach(o -> innerList
.stream()
//Filter to get those Inners for which the Key equals the Key of this Outer
.filter(i -> innerKeyFunc.apply(i).equals(outerKeyFunc.apply(o)))
.forEach(i -> {
if (matches.containsKey(o)) {
//This Outer already had matches,so add this Inner to the List
matches.get(o).add(i);
} else {
//This is the first Inner to match this Outer,so create a List
List list = new ArrayList<>();
list.add(i);
matches.put(o,list);
}
}));
matches.forEach((out,in) -> in.stream()
//Map each (Outer,Inner) pair to the appropriate Result...
.map(i -> resultFunc.apply(out,i))
//...and collect them
.forEach(res -> results.add(res)));
//Return the result as a Stream,like the .NET method does (IEnumerable)
return results.stream();
}
我只使用以下输入对代码进行了简短测试:
public static void main(String[] args) {
Stream strings = Arrays.asList("a","b","c","e","f","d").stream();
Stream ints = Arrays.asList(1,2,3,6,5,4).stream();
Stream results = join(strings,ints,Function.identity(),str -> Integer.parseInt(str,16) - 9,(o,i) -> "Outer: " + o + ",Inner: " + i);
results.forEach(r -> System.out.println(r));
}
> int是他们自己的键,所以没有转换
>字符串根据其十六进制值映射到整数 – 9
>(如果int值相等,则元素匹配,默认情况下)
>匹配对被放入String中
打印以下(正确)结果:
Outer: a,Inner: 1
Outer: b,Inner: 2
Outer: c,Inner: 3
Outer: d,Inner: 4
Outer: e,Inner: 5
Outer: f,Inner: 6
当然,还需要进行更深入的测试,但我认为这种实施是正确的.它可能也更有效率,我愿意接受建议.