Andrew Mairose
Andrew Mairose

Reputation: 10995

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

Upvotes: 8

Views: 14602

Answers (1)

Andrew Mairose
Andrew Mairose

Reputation: 10995

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

Upvotes: 16

Related Questions