Reputation: 1
I want to use the stream api sorting with a Comparator parameter but it doesn't sort properly. I always get exception.
I want to sort an object with a reference to another object, and the referenced object has a String so I want to sort it to its length.
This is my main method.
List<Person> liste = Arrays.asList(new Person(new Info("akin"))
,new Person(new Info("lars"))
,new Person(new Info("aaa")));
liste.stream()
.map(p -> p.f)
.map(f -> f.name)
.sorted((s,s2) -> s.length() - s2.length())
.forEach(System.out::print);
Upvotes: 0
Views: 77
Reputation: 37
I'll make an assumption here because your stream code looks good.
I assume that in at least one of the two constructors (either for Person
or for Info
) you didn't assign the incoming value properly to the instance field, hence it is null and trying to get f.name
or [f.name].length()
will lead to a NullPointerException.
Below is a working example of the stream that you posted (you will notice, I did not change anything in the code in your question except for some indentation).
import java.util.Arrays;
import java.util.List;
class Main {
public static void main(String[] args) {
List<Person> liste = Arrays.asList(new Person(new Info("akin")),
new Person(new Info("lars")),
new Person(new Info("aaa")));
liste.stream()
.map(p -> p.f)
.map(f -> f.name)
.sorted((s, s2) -> s.length() - s2.length())
.forEach(System.out::print);
}
static class Person {
Info f;
public Person(Info f) {
this.f = f;
}
}
static class Info {
String name;
public Info(String name) {
this.name = name;
}
}
}
Your constructor might look like
public Person(Info f) {
f = f;
}
(notice the missing this
compared to my example). This is a good read on uses of this
.
My IDE also suggested a minor change on the sorted
method. You can use Comparator#comparingInt which would look like this:
.sorted(Comparator.comparingInt(String::length))
This really comes down to what you think is more readable though.
For further reference on NullPointerExceptions please read the link that was already posted in the comments. This won't have been your last one ;)
Upvotes: 1