How to get the first 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(0, Math.min(list.size(), N));
        
        System.out.println(last);
    }
}



/*
run:

[java, php, c]

*/

 



answered Mar 18, 2021 by avibootz

Related questions

1 answer 162 views
1 answer 311 views
3 answers 223 views
1 answer 173 views
2 answers 151 views
1 answer 234 views
...