Solved Add players to a list when they join if they have certain permissions

Discussion in 'Spigot Plugin Development' started by Xurvold, Mar 28, 2020.

  1. So how would I add a player to a list if they have the permission plugin.use when they log on to the server?
     
    #1 Xurvold, Mar 28, 2020
    Last edited: Mar 28, 2020
  2. MrGeneralQ

    MrGeneralQ Previously qintinator
    Supporter

    List<Player> playerList = new ArrayList();

    if(player.hasPermission("plugin.use")){
    playerList.add(player);
    }

    Or use a lambda

    List<Player> playerList = Bukkit.getOnlinePlayers().stream().filter(p -> p.hasPermission("plugin.use").collect(Collectors.List);
     
  3. Choco

    Moderator

    What is it you're trying to do so we can assess whether a List is even the appropriate collection or whether or not holding a reference to the Player is even necessary. You might only need a Set<UUID>. More information, please.

    You're missing type inference on instantiation. <>
     
    • Like Like x 1
  4. I want to send them a notification every time diamond block is being mined.
    I thought it would be best to use a list so they can turn the notifications off whenever needed but have it on by default.
     
  5. Hello,

    Then you should just listen to the BlockBreakEvent, check if it's a diamond block, iterate over all Bukkit.getOnlinePlayers() and send a message to the player who have the permission 'plugin.use'.
    If you want to turn on/off notifications, just create a Set<UUID>, add the player who deactivated notification in it, and when you iterate over the onlines players to send a message, check if the player is in the deactivated set or not.
     
  6. Choco

    Moderator

    I would say have it be the other way around. Avoid the PlayerJoinEvent all together and don't send the alert in a BlockBreakEvent if the player IS in a list. This way you can add them to a set from the command rather than adding in an event and removing in a command. Though for this, a Set<UUID> is most definitely the more optimal collection here.
    Code (Java):
    private final Set<UUID> ignoreMessages = new HashSet<>();
    In your command, if a player wants to ignore the messages, add their UUID to the set. In your block break listener, if the set does not contain their UUID, send the message.

    The reason for a HashSet over an ArrayList is because its #contains() operations are significantly quicker. O(1) > O(n). And UUID because you have no reason to hold an instance of Player as you're not making any operations on the Player instance itself. Holding its UUID will avoid any unnecessary memory leaks.
     
  7. I'll try it out and see how it works out for me.
    Both thank you for your tips!