Java 8 Streams如何避免使用map或set进行过滤? [英] Java 8 Streams how to avoid filtering with map or set?
问题描述
我不断遇到需要/认为我需要通过Map或Set保存状态的解决方案. 例如创建一个方法,该方法返回在输入中找到的重复项
I keep running into solutions where I want/think i need to save state via either a Map or a Set. e.g. create a method that returns duplicates found in the input
// non streams solution
public int[] getDuplicates(int[] input){
Set<Integer> allSet = new HashSet<Integer>();
Set<Integer> duplicates = new HashSet<Integer>();
int[] dups = new int[input.length];
int j = 0;
for (Integer i : input) {
if (!allSet.add(i)) {
if(duplicates.add(i)) {
dups[j++] = i;
}
}
}
return Arrays.copyOfRange(dups, 0, j);
}
不幸的是,我的Java 8 Streams解决方案使用的是HashSet进行过滤.我了解这不是适当的",因为它取决于状态. 没有国家提出建议或硬性规定吗?运行并行流时仅是一个问题吗?有人可以建议一种不使用HashSet的方法吗?
My Java 8 Streams solution, unfortunately I am using a HashSet for filtering. I understand this is not "proper" as it depends on state. Is no state a suggestion or a hard-fast rule? Is it only an issue when running a parallel stream? Can someone suggest a way not to use HashSet here?
public static int[] getDuplicatesStreamsToArray(int[] input) {
Set<Integer> allSet = new HashSet<>();
int[] dups = Arrays.stream(input)
.sequential() // prevents parallel processing
.unordered() // speed up distinct operation
.boxed() // int to Integer
.filter(n -> !allSet.add(n)) // passes dups, but uses STATE
.distinct() // uses internal Set of dups
.mapToInt(i -> i) // Integer back to int
.toArray();
return dups;
}
推荐答案
这是怎么回事:
基本上,创建类型为Map<Integer,Long>
的频率计数,并返回value
大于1的那些keys
.
Basically, creates a frequency count of type Map<Integer,Long>
and returns those keys
where the value
is greater than 1.
public static int[] getDuplicatesStreamsToArray(int[] input) {
int[] dups = Arrays.stream(input).boxed().collect(
Collectors.groupingBy(Function.identity(),
Collectors.counting())).entrySet().stream().filter(
e -> e.getValue() > 1).mapToInt(
e -> e.getKey()).toArray();
return dups;
}
我误解了你以前想做什么.
I misunderstood what you were trying to do earlier.
这篇关于Java 8 Streams如何避免使用map或set进行过滤?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!