Predicate tips

In our example for creating a party system, we ended up having lots of code repetition. In our party creation command, we had the following code:

List<Argument> arguments = new ArrayList<>();

// The "create" literal, with a requirement that a player must have a party
arguments.add(new LiteralArgument("create")
	.withRequirement(sender -> {
		
		return !partyMembers.containsKey(((Player) sender).getUniqueId());
		
	}));

arguments.add(new StringArgument("partyName"));

And for our party teleportation command, we had the following code:

arguments = new ArrayList<>();
arguments.add(new LiteralArgument("tp")
	.withRequirement(sender -> {
		
		return partyMembers.containsKey(((Player) sender).getUniqueId());
        
	}));

We can simplify this code by declaring the predicate:

Predicate<CommandSender> testIfPlayerHasParty = sender -> {
    return partyMembers.containsKey(((Player) sender).getUniqueId());
};

Now, we can use the predicate testIfPlayerHasParty in our code for creating a party. Since we want to apply the "not" (!) operator to this predicate, we can use .negate() to invert the result of our predicate:

List<Argument> arguments = new ArrayList<>();
arguments.add(new LiteralArgument("create").withRequirement(testIfPlayerHasParty.negate()));
arguments.add(new StringArgument("partyName"));

And we can use it again for our code for teleporting to party members:

arguments = new ArrayList<>();
arguments.add(new LiteralArgument("tp").withRequirement(testIfPlayerHasParty));