String in ArrayList <Long>

I currently have:

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

      

I can turn it into a list of arrays of strings and then into a list of Longs arrays:

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 it with help Stream

to make it more "fun", but it seems to fail with this:

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

      

I don't think the for loop is very nifty, how can I do it with Stream

?

Edit: copied to original line incorrectly

+3


source to share


3 answers


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

:

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

      

Also, it Collectors.toList()

will return an interface List

, not a specific implementation ArrayList

.



If you really want a list of arrays, you need to copy it:

new ArrayList<>(longs);

      

Edit:
As @shmosel pointed out, you can directly collect a list of arrays withCollectors.toCollection(ArrayList::new)

+7


source


You cannot pass String

without dividing it. Two ways to split into a stream:

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

      

or



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

      

It also collect(Collectors.toList())

returns List

instead of ArrayList

. And I'm not sure why you expect it parseLong()

to work with these lines.

+4


source


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: used here Doubles#tryParse

from Guava.

+1


source







All Articles