简体   繁体   English

Java stream - map 并将 int 数组存储到 Set

[英]Java stream - map and store array of int into Set

I have an array of [5, 6, 7, 3, 9] , I would like to change each element from the array substracting by 2, then store the in a Set , so what I did is我有一个[5, 6, 7, 3, 9]数组,我想更改数组中的每个元素减去 2,然后将其存储在Set中,所以我所做的是

Set<Integer> mySet = Arrays.stream(arr1).map(ele -> new Integer(ele - 2)).collect(Collectors.toSet());

but I am getting two exceptions here as但我在这里遇到两个例外

  1. The method collect(Supplier<R>, ObjIntConsumer<R>, BiConsumer<R,R>) in the type IntStream is not applicable for the arguments (Collector<Object,?,Set<Object>>) " The method collect(Supplier<R>, ObjIntConsumer<R>, BiConsumer<R,R>) in the type IntStream is not applicable for the arguments (Collector<Object,?,Set<Object>>) "
  2. Type mismatch: cannot convert from Collector<Object,capture#1-of?,Set<Object>> to Supplier<R>

What does those error mean and how can I fix the issue here with Java Stream operation?这些错误是什么意思,我该如何解决Java Stream操作的问题?

It looks like arr1 is an int[] and therefore, Arrays.stream(arr1) returns an IntStream .看起来arr1是一个int[] ,因此, Arrays.stream(arr1)返回一个IntStream You can't apply .collect(Collectors.toSet()) on an IntStream .您不能在 IntStream 上应用IntStream .collect(Collectors.toSet())

You can box it to a Stream<Integer> :您可以将其装箱到Stream<Integer>

Set<Integer> mySet = Arrays.stream(arr1)
                           .boxed()
                           .map(ele -> ele - 2)
                           .collect(Collectors.toSet());

or even simpler:甚至更简单:

Set<Integer> mySet = Arrays.stream(arr1)
                           .mapToObj(ele -> ele - 2)
                           .collect(Collectors.toSet());

Arrays.stream(int[]) returns an IntStream . Arrays.stream(int[])返回一个IntStream And IntStream does not offer collect() methods that take a Collector .并且IntStream不提供采用Collectorcollect()方法。

If you need to use Collectors.toSet() , then you need a Stream<Integer> for it, and you can call mapToObj for that:如果你需要使用Collectors.toSet() ,那么你需要一个Stream<Integer> ,你可以为此调用mapToObj

Set<Integer> mySet = Arrays.stream(arr1)
                           .mapToObj(ele -> ele - 2)
                           .collect(Collectors.toSet());

If you're open to using a third-party library, you can avoid boxing the int values as Integer using Eclipse Collections IntSet .如果您愿意使用第三方库,则可以避免使用Eclipse Collections IntSetint值装箱为Integer

int[] array = {5, 6, 7, 3, 9};
IntStream stream = Arrays.stream(array).map(value -> value - 2);
IntSet actual = IntSets.mutable.ofAll(stream);
IntSet expected = IntSets.mutable.of(3, 4, 5, 1, 7);
Assert.assertEquals(expected, actual);

Note: I am a committer for Eclipse Collections.注意:我是 Eclipse Collections 的提交者。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM