Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java stream remove first three elements

I have list of object sorted by student id:

List<Student> arraylist = new ArrayList<>();
arraylist.add(new Student(1, "Chaitanya", 26));
arraylist.add(new Student(2, "Chaitanya", 26));
arraylist.add(new Student(3, "Rahul", 24));
arraylist.add(new Student(4, "Ajeet", 32));
arraylist.add(new Student(5, "Chaitanya", 26));
arraylist.add(new Student(6, "Chaitanya", 26));

I would like to use stream and remove only first three elements where student age equals 26. Could you please help me with this.

like image 431
Artifex Avatar asked Dec 01 '25 05:12

Artifex


1 Answers

You can use filter and skip as :

List<Student> finalList = arraylist.stream()
        .filter(a -> a.getAge() == 26) // filters the students with age 26
        .skip(3) // skips the first 3 
        .collect(Collectors.toList());

This will result in listing Students with age equal to 26 while at the same time skipping first three occurrences of such students.


On the other hand, if you just want to exclude those three students from the complete list, you can also do it as:

List<Student> allStudentsExcludingFirstThreeOfAge26 = Stream.concat(
            arraylist.stream().filter(a -> a.getAge() != 26),
            arraylist.stream().filter(a -> a.getAge() == 26).skip(3))
        .collect(Collectors.toList());

Do note, that this could result in changing the original order of the list.

like image 136
Naman Avatar answered Dec 03 '25 17:12

Naman