简体   繁体   中英

Java8 Stream - HashSet of Byte from IntStream

I'm trying to create a HashSet<Byte> of byte s 1, 2, 3, ... 9 with the Java 8 Streams API. I thought using IntStream and then downgrading the values to byte would do it.

I'm trying variations of

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 those 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 flatMap or mapToObject ?

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

You could use a MutableByteSet from Eclipse Collections with the IntStream and avoid the 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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