non ho trovato alcun equivalente esistente, ma il metodo di seguito dovrebbe funzionare:
public static <Outer, Inner, Key, Result> Stream<Result> join(
Stream<Outer> outer, Stream<Inner> inner,
Function<Outer, Key> outerKeyFunc,
Function<Inner, Key> innerKeyFunc,
BiFunction<Outer, Inner, Result> resultFunc) {
//Collect the Inner values into a list as we'll need them repeatedly
List<Inner> innerList = inner.collect(Collectors.toList());
//matches will store the matches between inner and outer
final Map<Outer, List<Inner>> matches = new HashMap<>();
//results will be used to collect the results in
final List<Result> 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<Inner> 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();
}
ho fatto solo un breve test del codice utilizzando i seguenti ingressi:
public static void main(String[] args) {
Stream<String> strings = Arrays.asList("a", "b", "c", "e", "f", "d").stream();
Stream<Integer> ints = Arrays.asList(1, 2, 3, 6, 5, 4).stream();
Stream<String> 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));
}
- I
int
s sono le proprie chiavi, s o nessuna trasformazione
- Il
Strings
sono mappati int
s secondo il loro valore esadecimale - 9
- (Gli elementi corrispondono se i valori
int
sono uguali, come da default)
- accoppiamenti sono messi in una
String
La seguente (corretto) risultati vengono stampati:
Outer: a, Inner: 1
Outer: b, Inner: 2
Outer: c, Inner: 3
Outer: d, Inner: 4
Outer: e, Inner: 5
Outer: f, Inner: 6
più approfonditi test saranno b E 'necessario, ovviamente, ma credo che questa implementazione sia corretta. Potrebbe anche essere più efficiente, sono aperto a suggerimenti.
Quasi sicuramente dovresti scaricare entrambi i flussi in mappe sulla chiave specificata, quindi unire direttamente le mappe. Gli stream Java non sono realmente progettati per essere combinati in alcun modo se non la concatenazione. –