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.

3
  • Quick Reference to: stackoverflow.com/questions/4439595/… In short: You can use the function Array.copyOfRange(Object [], int from, int to) Commented Jan 28, 2022 at 19:57
  • 1
    @Raqha the source is a list, not an array. Commented Jan 28, 2022 at 19:59
  • Jsid, if I answered your question satisfactory, please select my answer by clicking the checkmark. Thanks. Commented Jan 28, 2022 at 20:06

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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
@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)
0

Try reading about Java 8 Stream API, specifically:

This should help you achieve what you need.

Comments

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]] } } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.