I have a List<String>
that I would like converted to a List<Long>
. Before Java 8, I would do this by looping through the List<String>
, converting each String
to a Long
and adding it to the new List<Long>
, as shown below.
List<String> strings = /* get list of strings */;
List<Long> longs = new ArrayList<>();
for (final String string : strings) {
longs.add(Long.valueOf(string));
}
However, I need to do this conversion using Java 8 streams, as the conversion is part of a larger stream operation. I have the List<String>
as a stream, as if I had done strings.stream()
. So, how could I perform this conversion, similar to something like this.
List<String> strings = /* get list of strings */;
List<Long> longs = strings.stream().map(/*convert to long*/).collect(Collectors.toList());
There are many methods for converting a String to a Long data type in Java which are as follows: Using the parseLong() method of the Long class. Using valueOf() method of long class. Using constructor of Long class.
Conversion Using chars() The String API has a new method – chars() – with which we can obtain an instance of Stream from a String object. This simple API returns an instance of IntStream from the input String.
2.2.Any stream in Java can easily be transformed from sequential to parallel. We can achieve this by adding the parallel method to a sequential stream or by creating a stream using the parallelStream method of a collection: List<Integer> listOfNumbers = Arrays.
Solution was very simple. Just needed to use Long::valueOf
.
List<Long> longs = strings.stream().map(Long::valueOf).collect(Collectors.toList());
OR Long::parseLong
List<Long> longs = strings.stream().map(Long::parseLong).collect(Collectors.toList());
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