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
?
In this tutorial, We'll learn how to use the IntStream in java 8 and it uses with example programs. For int primitives, the Java IntStream class is a specialization of the Stream interface. It's a stream of primitive int-valued items that can be used in both sequential and parallel aggregate operations.
Stream of String tokens // 3. Set<String> to HashSet<String> ? 2. Using Collectors.toCollection () Convert Stream to HashSet using collect () method of Stream API by passing Collectors.toCollection (HashSet::new) as input argument directly
Introduction The Stream API was one of the key features added in Java 8. Briefly, the API allows us to process collections and other sequences of elements – conveniently and more efficiently – by providing a declarative API. 2. Primitive Streams Streams primarily work with collections of objects and not primitive types.
Using Collectors.toSet () First, convert Stream to Set using collect () method of Stream API by passing Collectors.toSet () as input argument For Set to HashSet conversion, create HashSet object and pass above set as constructor-argument ? // 1. Stream of String tokens // 3. Set<String> to HashSet<String> ? 2. Using Collectors.toCollection ()
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With