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
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)
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.
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