java set 过滤,Java 8 Streams如何避免使用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 allSet = new HashSet();

Set duplicates = new HashSet();

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);

}

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 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;

}

解决方案

How about this:

Basically, creates a frequency count of type Map 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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值