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 145 views
1 answer 157 views
1 answer 127 views
2 answers 259 views
2 answers 244 views
1 answer 171 views
1 answer 144 views
...