Reputation: 313
I am new to Streams, I have a list of long values. And I want to convert the list of long values to list of double values using stream.
Here is the code:
List<Long> list = new ArrayList<>();
list.add(4L);
list.add(92L);
list.add(100L);
I want to convert the list to a List<double>
. Thanks
Upvotes: 3
Views: 2226
Reputation: 6686
You can do this without boxing long
and double
values using Eclipse Collections:
LongList longs = LongLists.mutable.with(4L, 92L, 100L);
DoubleList doubles = longs.collectDouble(l -> l, DoubleLists.mutable.empty());
Assert.assertEquals(DoubleLists.mutable.with(4.0, 92.0, 100.0), doubles);
You can also do this with Java Streams and Eclipse Collections converting from a List<Long>
to a DoubleList
:
List<Long> list = Arrays.asList(4L, 92L, 100L);
DoubleList doubles = DoubleLists.mutable.withAll(
list.stream().mapToDouble(Long::doubleValue));
Assert.assertEquals(DoubleLists.mutable.with(4.0, 92.0, 100.0), doubles);
Note: I am a committer for Eclipse Collections
Upvotes: 2
Reputation: 21124
You have to use the map
operator to convert Long
into a Double
and then use the toList
collector.
List<Double> doubleValues = list.stream()
.map(Double::valueOf)
.collect(Collectors.toList());
Conversely, if you are concerned about the overhead of autoboxing, you can create an array of double
. Here's how it looks.
double[] doubleArr = list.stream().mapToDouble(v -> v).toArray();
Upvotes: 6
Reputation: 51
You have to use the mapToDoubleoperator to convert Long into a Double and then use the toList collector.
List<Long> longs = new ArrayList<>();
longs.add(2316354L);
longs.add(2456354L);
longs.add(888354L);
List<Double> doubles = longs.stream().mapToDouble(e->e).boxed().collect(Collectors.toList());
Upvotes: 1
Reputation: 6390
List<Double> collect1 = list.stream()
.mapToDouble(s -> s) // DoubleStream
.boxed() // Stream<Double>
.collect(Collectors.toList()); //collected to List<Double>
caution: boxing()
is overhead.
Another way around, without boxing()
List<Double> listDouble = new ArrayList<>();
list.stream().mapToDouble(s->s).forEach(k->listDouble.add(k));
Upvotes: 3
Reputation: 9437
Try something in the line of:
List<Double> doubles = list.stream()
.map(e -> Double.valueOf(e))
.collect(Collectors.toList());
Explanation
list.stream().
This makes you create (and iterate over) a stream.
map(e -> Double.valueOf(e))
each (Long) element you iterate over, will be mapped to a Double
.collect(Collectors.toList());
This maps it to a List<Double>
.
Upvotes: 3