问题
I need to get only unique values from the collection( values which do not have any dublicates in collection). For example, this code:
ArrayList<Integer> g = new ArrayList<>(Arrays.asList(1,1,2,2,3,4,5,5,5,6,6));
System.out.println(Arrays.toString(g.stream().mapToInt(Integer::intValue).distinct().toArray()));
gives me this result:
[1, 2, 3, 4, 5, 6]
However I want the result:
[3, 4]
Is there any way to do it with Stream API?
回答1:
List<Integer> source = Arrays.asList(1, 1, 2, 2, 3, 4, 5, 5, 5, 6, 6);
List<Integer> processed = source.stream()
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
.entrySet().stream()
.filter(e -> e.getValue() == 1)
.map(Map.Entry::getKey)
.collect(Collectors.toList());
System.out.println(processed);
Result:
[3, 4]
回答2:
You can do it as follows:
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
public class Collusion {
public static void main(String[] args) {
List<Integer> g = Arrays.asList(1, 1, 2, 2, 3, 4, 5, 5, 5, 6, 6);
System.out.println(g.stream().filter(x -> Collections.frequency(g, x) < 2).collect(Collectors.toList()));
}
}
Output:
[3, 4]
来源:https://stackoverflow.com/questions/60605971/print-unique-values-from-collection-using-stream-api