Get the nth element from the list using the Java stream

I have a list of strings, such as "/ 100" "/ 100 / 200"

As we all know, the length n of each internal list is the largest

Example:

n= 3
slashString -> "/100/200/300","/200/300","/100/200/400"

In the above example, I want a list of integers as 300, 400

List<Integer> output = slashString.stream()
        .map(x->Arrays.stream(x.split("/")).collect(Collectors.toList()))
        .filter(x->x.size()==3)

I can think about it How do I finally collect the third element in the list of all integers

Solution

Just map each list to the third element of the list and collect:

List<Integer> list = Stream.of ("100/200/300","200/300","100/200/400")
    .map(x->Arrays.stream(x.split("/")).collect(Collectors.toList()))
    .filter(x->x.size()==3)
    .map(l->Integer.valueOf (l.get(2)))
    .collect(Collectors.toList());

Note that you must eliminate the leading /. Of the input string Otherwise, the length of lists 1 and 3 will be 4 and they will not pass the filter Alternatively, you can require the list size to be 4 instead of 3 (and change L.Get (2) to L.Get (3))

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>