Use Java streams to get nth element from a list

  • A+
Category:Languages

I have a list of Strings such as "/100" "/100/200". I wish to split these strings by "/", and would then get a List of List of Integers such as [[100],[100,200]]. I want to traverse this list of list and get nth element from each list if that list is long enough, else move to the next list.

It is known that each inner list would be maximum of length n. Example

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

In the above case 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 am able to think till above. How would I eventually collect the 3rd element across all the list of integers.

 


Just map each List to the 3rd 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 have to eliminate the leading / of the input Strings. Otherwise the lengths of the 1st and 3rd Lists will be 4, and they won't pass the filter. Or you can require the List size to be 4 instead of 3 (and change l.get(2) to l.get(3)).

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: