Home > Mobile >  How to get first and second element of a each list in a nested list in java
How to get first and second element of a each list in a nested list in java

Time:01-29

Right now I have an Arraylist in java. When I call

myarraylist.get(0)
myarraylist.get(1)
myarraylist.get(2)

[0, 5, 10, 16]
[24, 29, 30, 35, 41, 45, 50]
[0, 6, 41, 45, 58]

are all different lists. What I need to do is get the first and second element of each of these lists, and put it in a list, like so:

[0,5]
[24,29]
[0,6]

I have tried different for loops and it seems like there is an easy way to do this in python but not in java.

CodePudding user response:

List<Integer> sublist = myarraylist.subList(0, 2);

For List#subList(int fromIndex, int toIndex) the toIndex is exclusive. Therefore, to get the first two elements (indexes 0 and 1), the toIndex value has to be 2.

CodePudding user response:

Try reading about Java 8 Stream API, specifically:

This should help you achieve what you need.

CodePudding user response:

  1. Map through nested lists.
  2. Create a sub-list of each nested list.
  3. Collect the stream back into a new list.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

class Scratch {
    public static void main(String[] args) {
       List<List<Integer>> myArrayList = new ArrayList<>();
       myArrayList.add(Arrays.asList(0, 5, 10, 16));
       myArrayList.add(Arrays.asList(24, 29, 30, 35, 41, 45, 50));
       myArrayList.add(Arrays.asList(0, 6, 41, 45, 58));

        System.out.println(myArrayList.stream().map(l -> l.subList(0, 2)).collect(Collectors.toList()));
        // [[0, 5], [24, 29], [0, 6]]
    }
}
  •  Tags:  
  • Related