Reputation: 1082
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
Upvotes: 4
Views: 3991
Reputation: 856
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)
Upvotes: 10
Reputation: 5443
String a = "123.5950.555,5973.1,6321.905,6411.810000000001,6591.855";
List<Double> doubleList = Arrays.stream(a.split(","))
.map(Doubles::tryParse)
.collect(Collectors.toList());
System.out.println(doubleList);
Note: this uses Doubles#tryParse
from Guava.
Upvotes: 1
Reputation: 50716
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.
Upvotes: 4