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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With