Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert stream of Strings to stream of Longs

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());
like image 531
Andrew Mairose Avatar asked Aug 24 '15 16:08

Andrew Mairose


People also ask

Can I cast from string to long?

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.

Can we convert string to stream?

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.

Can all streams be converted to parallel stream?

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.


1 Answers

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());
like image 165
Andrew Mairose Avatar answered Sep 19 '22 10:09

Andrew Mairose