Java8 Stream - 来自IntStream的字节的HashSet

时间:2017-05-20 02:38:43

标签: java java-stream

我尝试使用Java 8 Streams API创建HashSet<Byte> byte s 1, 2, 3, ... 9。我想使用IntStream然后将值降级为byte就可以了。

我尝试了

的变体

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

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

但这些都没有奏效。

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)

我需要flatMap还是mapToObject

2 个答案:

答案 0 :(得分:6)

您需要使用mapToObj,因为HashSet和所有泛型都需要对象

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

答案 1 :(得分:1)

您可以使用MutableByteSet IntStream ByteSet byteSet = IntStream.range(1, 10) .collect(ByteSets.mutable::empty, (set, i) -> set.add((byte) i), MutableByteSet::addAll); // The IV needs to be unique, but not secure. Therefore it's common to // include it at the beginning of the ciphertext. ... iv := ciphertext[:aes.BlockSize] ciphertext = ciphertext[aes.BlockSize:] 来避免拳击。

ciphertext

注意:我是Eclipse Collections的提交者

相关问题