How to get the last N elements from list in Java

1 Answer

0 votes
import java.util.List;
import java.util.Arrays;
 
public class MyClass {
    public static void main(String args[]) {
        List<String> list = Arrays.asList("java", "php", "c", "c++", "python", "c#"); 
 
        int N = 3;
        List<String> last = list.subList(Math.max(list.size() - N, 0), list.size());
         
        System.out.println(last);
    }
}
 
 
 
/*
run:
 
[c++, python, c#]
 
*/

 



answered Mar 18, 2021 by avibootz
edited Mar 18, 2021 by avibootz

Related questions

1 answer 230 views
1 answer 227 views
1 answer 204 views
2 answers 372 views
1 answer 248 views
1 answer 220 views
2 answers 356 views
...