Java8 Stream - HashSet bytes from IntStream

I am trying to create HashSet<Byte>from byte 1, 2, 3, ... 9using the Java 8 Streams APIs. I thought of using IntStreamand then overriding the values ​​to byte.

I'm trying to change

HashSet<Byte> nums = IntStream.range(1, 10).collect(Collectors.toSet());

HashSet<Byte> nums = IntStream.range(1, 10).map(e -> ((byte) e)).collect(Collectors.toSet());

But none of them work.

Error:(34, 73) java: method collect in interface java.util.stream.IntStream cannot be applied to given types;
  required: java.util.function.Supplier<R>,java.util.function.ObjIntConsumer<R>,java.util.function.BiConsumer<R,R>
  found: java.util.stream.Collector<java.lang.Object,capture#1 of ?,java.util.Set<java.lang.Object>>
  reason: cannot infer type-variable(s) R
    (actual and formal argument lists differ in length)

Do I need to do flatMapor mapToObject?

+6
source share
2 answers

You need to use mapToObj since HashSet and all generics require objects

Set<Byte> nums = IntStream.range(1, 10)
    .mapToObj(e -> (byte) e)
    .collect(Collectors.toSet());
+6
source

You can use MutableByteSetfrom Eclipse Collections with help IntStreamand avoid boxing.

ByteSet byteSet = IntStream.range(1, 10)
        .collect(ByteSets.mutable::empty,
                (set, i) -> set.add((byte) i),
                MutableByteSet::addAll);

Note: I am a committer for Eclipse collections

+1
source

Source: https://habr.com/ru/post/1017404/


All Articles