Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to remove under 18 years old from list?

I try to remove all the person under 18 years old from my list,
so i have a class Person and this is what i tried in my Main:

import java.util.*;

public class Main {

    public static void main(String[] args) {
       
        Person person1 = new Person("Victor", 28, "meerdonk");
        Person person2 = new Person("Alex", 17, "antwerpen");
        Person person3 = new Person("Vlad", 15, "mechelen");

        List<Person> listOfPersons = List.of(person1, person2, person3);
   
        List<Person> adults = getLessThen18(listOfPersons); **//line 22**
        System.out.println(adults);
}   
 public static List<Person> getLessThen18(List<Person> personList) {

       for (Iterator<Person> iterator = personList.listIterator(); iterator.hasNext();){
           if (iterator.next().getAge() < 18 ) {
                iterator.remove(); **//line 40**
           }
       }
        return personList;
    }
}

So I try to iterate trough the list of persons and then if the person is under 18 to remove it.
As i run the code i get this output :

Exception in thread "main" java.lang.UnsupportedOperationException
    at java.base/java.util.ImmutableCollections.uoe(ImmutableCollections.java:142)
    at java.base/java.util.ImmutableCollections$ListItr.remove(ImmutableCollections.java:380)
    at victor.Main.getLessThen18Iteration(Main.java:40)
    at victor.Main.main(Main.java:22)

Can someone please let me know what I did wrong?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Your code (List.of) creates an immutable list of persons:

    List<Person> listOfPersons = List.of(person1, person2, person3);

So calling remove/add will cause an Exception – as in your case.

Also your method name is misleading, since you are changing/mutating the passed list parameter and not return a new list (as suggested by the return value).

A possible way to do it would be:

 public static List<Person> getLessThen18(List<Person> personList) {
    return personList.stream()
                     .filter(person -> person.getAge() < 18)
                     .collect(Collectors.toList());   
 }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading