ronan
ronan

Reputation: 4672

Remove null objects from a List of Student objects

I was exploring Java 8 feature to remove null objects from a List of say Student objects and I have the following code

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;

public class Student {

    private String name;

    public Student(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "Student {" + "name=" + name + "}";
    }

    public static Comparator<Student> getNameComparator() {

        return (s1, s2) -> s1.name.compareTo(s2.name);
        // return Comparator.comparing(x -> x.name,
        // Comparator.nullsLast(Comparator.naturalOrder()));
    }

    public static void main(String[] args) {

        List<Student> ls = new ArrayList<>(
                Arrays.asList(new Student("Dino"), new Student(null), new Student("Fred"), new Student("Amy")));
        // ls.removeAll(Collections.singleton(null));
        ls.removeIf(Objects::isNull);
        ls.forEach(s -> System.out.println(s));
        System.out.println("...............................");
        ls.sort(Student.getNameComparator());
        ls.forEach(s -> System.out.println(s));

    }

}

I have used java 8 specific isNull i.e ls.removeIf(Objects::isNull); still in the o/p I see null value i.e O/p is

Student {name=Dino} Student {name=null} Student {name=Fred} Student {name=Amy}

Am I missing on something specific ?

Thanks Ronan

Upvotes: 1

Views: 518

Answers (1)

roookeee
roookeee

Reputation: 1828

removeIf(Objects::isNull) is removing any Student object in the given list that is null, not every Student whichs name is null. You can achieve what you want with .removeIf(student -> student.getName() == null)

Upvotes: 3

Related Questions