Duke Jake Morgan Duke Jake Morgan - 17 days ago 7
Java Question

Method reference and boolean

So I have been having a go with using the method reference in Java 8 (Object::Method). What I am attempting to do, which I have done before but have forgotten (last time I used this method reference was about 4 months ago), is find the amount of players that != online using the Method Reference.

public static Set<Friend> getOnlineFriends(UUID playerUUID)
{
Set<Friend> friends = new HashSet<>(Arrays.asList(ZMFriends.getFriends(playerUUID)));

return friends.stream().filter(Friend::isOnline).collect(Collectors.toSet());
}

public static Set<Friend> getOfflineFriends(UUID playerUUID)
{
Set<Friend> friends = new HashSet<>(Arrays.asList(ZMFriends.getFriends(playerUUID)));

return friends.stream().filter(Friend::isOnline).collect(Collectors.toSet());


As you can see I managed to so it when the player (friend) is online but I cannot figure out how to filter though the Set and collect the offline players. I'm missing something obvious, but what is it?!?!

Thanks,
Duke.

Answer

There are 2 ways I can think of:

friends.stream().filter(i -> !i.isOnline()).collect(Collectors.toSet());

But I guess that's not what you want, since it's not using a method reference. So maybe something like this:

public static <T> Predicate<T> negation(Predicate<T> predicate) {
    return predicate.negate();
}
...
friends.stream().filter(negation(Friend::isOnline)).collect(Collectors.toSet());
Comments