Ramesh K:
Atualmente tenho um programa Java que usa aninhados loops para computar a união e intersecção de uma lista de conjunto de inteiros. Como fazer isso usando java paralelas streams? O código que eu tenho atualmente é a seguinte
for(Set<Integer> x : listA) {
for (Set<Integer> y : listB) {
Set u = Sets.union(x,y); // Uses Guava library
Set i = Sets.intersection(x,y);
}
}
Eu gostaria de fazer isso rápido quanto listaA e listaB são grandes.
Darshan Mehta:
Você não precisa de fluxos para a união, no entanto, você pode usá-lo para cruzamento, por exemplo:
Set<Integer> setA = new HashSet<>(Arrays.asList(1,2,3));
Set<Integer> setB = new HashSet<>(Arrays.asList(2,3,4));
Set<Integer> union = new HashSet<>();
union.addAll(setA);
union.addAll(setB);
Set<Integer> intersection = setA.parallelStream()
.filter(setB::contains)
.collect(Collectors.toSet());
System.out.println("Union : " + union);
System.out.println("Intersection : " +intersection);
Atualizar
O código acima encontra intersecção e união usando bibliotecas nativas de Java e streams
. No entanto, se você tem uma lista de conjuntos, em seguida, você pode quebrar o código acima na função e chamá-lo de stream
que itera duas listas, por exemplo:
private static void unionAndIntersection(Set<Integer> setA, Set<Integer> setB) {
Set<Integer> union = new HashSet<>();
union.addAll(setA);
union.addAll(setB);
Set<Integer> intersection = setA.parallelStream()
.filter(setB::contains)
.collect(Collectors.toSet());
System.out.println("Union : " + union);
System.out.println("Intersection : " +intersection);
}
public static void main(String[] args){
List<Set<Integer>> listA = new ArrayList<>();
List<Set<Integer>> listB = new ArrayList<>();
listA.stream()
.forEach(a -> {
listB.stream()
.forEach(b -> unionAndIntersection(a, b));
});
}