简体   繁体   English

Java8 Stream - 来自IntStream的字节的HashSet

[英]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. 我正在尝试使用Java 8 Streams API创建byte s 1, 2, 3, ... 9HashSet<Byte> I thought using IntStream and then downgrading the values to byte would do it. 我想使用IntStream ,然后将值降级为byte就可以了。

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 ? 我需要做flatMapmapToObject吗?

You need to use mapToObj since HashSet and all generics require Objects 您需要使用mapToObj,因为HashSet和所有泛型都需要对象

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. 你可以使用一个MutableByteSetEclipse的收藏IntStream和避免装箱。

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 注意:我是Eclipse Collections的提交者

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

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