0

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.

Jsid Xbend
  • 1
  • 1
  • 2
  • Quick Reference to: https://stackoverflow.com/questions/4439595/how-to-create-a-sub-array-from-another-array-in-java In short: You can use the function `Array.copyOfRange(Object [], int from, int to)` – Raqha Jan 28 '22 at 19:57
  • 1
    @Raqha the source is a list, not an array. – hfontanez Jan 28 '22 at 19:59
  • Jsid, if I answered your question satisfactory, please select my answer by clicking the checkmark. Thanks. – hfontanez Jan 28 '22 at 20:06

3 Answers3

2

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.

hfontanez
  • 5,774
  • 2
  • 25
  • 37
  • this makes sense, but why 0 to 2? Shouldn't it be 0 to 1? Since the indexes of 0,5 on the first list are 0 and 1, not 0, 1, and 2 – Jsid Xbend Jan 28 '22 at 20:37
  • @JsidXbend because the `toIndex` value is EXCLUSIVE, meaning the last index is the value before (i.e. for `toIndex` == 2 , the last INCLUDED index is 1) – hfontanez Jan 28 '22 at 20:49
0

Try reading about Java 8 Stream API, specifically:

This should help you achieve what you need.

Orr Benyamini
  • 395
  • 2
  • 9
0
  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]]
    }
}
steven7mwesigwa
  • 5,701
  • 3
  • 20
  • 34