Mr Mosby
Mr Mosby

Reputation: 67

Copying last 3 elements of ArrayList into List<String>

I am currently trying to no avail to copy the final 3 elements of each iterating path into lastEdgePath. Furthermore, lastEdgePath has to be of type List < String > . List of Arraylists allPaths works and for this question it is to be assumed that it is populated. This is what I tried, what is currently happening is that the last 3 elements are added as 1 into lastEdgePath, while I need them to be added as the 3 different elements they are. Example: if path is [1,2,3,4,5,6] lastEdgePath would become [4,5,6]

public static List<ArrayList<String>> allPaths = new ArrayList<>();

for(ArrayList<String> path : allPaths){
      List<String> lastEdgePath = Collections.singletonList(path.get(path.size() - 3) + path.get(path.size() - 2) + path.get(path.size() - 1));
}

Upvotes: 1

Views: 79

Answers (2)

Jaeheon Shim
Jaeheon Shim

Reputation: 501

Just use the subList method.

public static List<ArrayList<String>> allPaths = new ArrayList<>();

for(ArrayList<String> path : allPaths){
      List<String> lastEdgePath = path.subList(path.size() - 3, path.size());
}

The one really important thing to note would be that this produces a view of the specified range meaning that any changes in the sublist will be reflected in the original list and vice versa.

Upvotes: 3

Andy Turner
Andy Turner

Reputation: 140318

Use subList:

List<String> lastThreeThings = path.subList(path.size() - 3, path.size());

Note that this is a view of the underlying list, so changes to lastThreeThings are reflected in path. If you need a separate list, copy it:

List<String> lastThreeThings = new ArrayList<>(path.subList(path.size() - 3, path.size()));

Also, note that this doesn't handle a list shorter than 3 elements. If that's a possibility, use Math.max(0, path.size() - 3) as the start index.

Upvotes: 3

Related Questions