简体   繁体   中英

Convert list of longs to list of doubles

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

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

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> .

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

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

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