Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String to ArrayList<Long>

Currently i have:

String a = "123.5950,555,5973.1,6321.905,6411.810000000001,6591.855"

I can turn it into an array list of Strings then into array list of Longs:

ArrayList<String> vals = new ArrayList<String>(Arrays.asList(a.split(","));
ArrayList<Long> longs = new ArrayList<>();

for(String ks : vals){
       longs.add(Long.parseLong(ks));
}

I tried to do this with Stream to make this more 'fun' but cant seem to be successful with this:

ArrayList<Long> longs = a.stream().map(Long::parseLong).collect(Collectors.toList());

I dont think the for loop is very elegant, how can i do it with Stream?

Edit: copied to original string wrong

like image 941
OrangePot Avatar asked Dec 05 '22 14:12

OrangePot


2 Answers

You need to create a stream from the result of String.split:

final List<Long> longs = Arrays
            .stream(a.split(","))
            .map(Long::parseLong)
            .collect(Collectors.toList());

Also, Collectors.toList() will return the List interface, not the concrete implementation ArrayList.

If you really need an array list, you'll need to copy it:

new ArrayList<>(longs);

Edit:
As @shmosel pointed out, you can collect directly to an array list with Collectors.toCollection(ArrayList::new)

like image 65
Joao Delgado Avatar answered Dec 20 '22 06:12

Joao Delgado


You can't stream a String without splitting it up. Two ways to split to stream:

Arrays.stream(a.split(","))

or

Pattern.compile(",").splitAsStream(a)

Aside from that, collect(Collectors.toList()) returns List, not ArrayList. And I'm not sure why you expect parseLong() to work on those strings.

like image 25
shmosel Avatar answered Dec 20 '22 08:12

shmosel