I have a list of Integer and would like to convert into a list of Long (or any other type) by using Streams. I tried multiple options but all failed. How do I do that?
List<Integer> arr = new ArrayList<Integer>();
arr.add(1);
arr.add(3);
arr.add(5);
arr.add(7);
arr.add(9);
CodePudding user response:
List<Long> longList = arr.stream().map(Long::valueOf).collect(Collectors.toList());
CodePudding user response:
Use:
List<Long> longList = arr.stream()
.map(Long::valueOf) //or map to any other type/objects with "e -> new..."
.collect(Collectors.toList());
CodePudding user response:
List<Integer> arr = new ArrayList<>();
...
List<Long> longs = arr.stream() // Stream<Integer>
.mapToLong(Integer::longValue) // LongStream
.boxed() // Stream<Long>
.collect(Collectors.toList());
List<Long> longs = arr.stream() // Stream<Integer>
.map(n -> Long.valueOf(n.longValue())) // Stream<Long>
.collect(Collectors.toList());
The latter uses Integer.longValue(), though Integer.intValue() would have done also. Relying on Integer to int unboxing and then Long.valueOf widening int to long, is too convoluted. Not sure whether there is a speed/memory difference. Should not.
Alternatively with a different data structure for arr:
IntStream arr = IntStream.of(1, 3, 5, 7, 9);
List<Long> longs = arr.asLongStream() // LongStream
.boxed() // Stream<Long>
.collect(Collectors.toList());
Basically you have to map an Integer to a Long.
