Get online players as string seperated by commas

Discussion in 'Plugin Development' started by ice374, Jul 24, 2013.

Thread Status:
Not open for further replies.
  1. Offline


    How do i do it? I have spent the last hour and a half trying but to no avail

    (if it comes down to it the commas aren't all that necessary along as there are spaces)

    Your time means a lot to me so I will follow whoever it is that helps me :)
  2. Offline



    StringBuilder players = new StringBuilder();
    for(Player p : getServer().getOnlinePlayers()) 
        players.append(p.getName()).append(", ");
    ice374 likes this.
  3. Offline


    This should do the trick
    		StringBuilder sb = new StringBuilder();
    		for(Player player : Bukkit.getServer().getOnlinePlayers()) {
    			sb.append(player.getName() + ", ");
    		String playerList = sb.toString();
    		Pattern pattern = Pattern.compile(", $");
    		Matcher matcher = pattern.matcher(playerList);
    		playerList = matcher.replaceAll("");
    The little bit with the regex should remove the final comma so that your list doesn't end with a comma.
    ice374 likes this.
  4. Offline


    StringBuilder is good, but Joiner is even more convenient:
    // one-liner!
    String playerList Joiner.on(", ").join(Bukkit.getServer().getOnlinePlayers());
    Edit: Sigh. As rsod correctly pointed out, that won't work, since getOnlinePlayers() returns an array of Player, not of String. StringBuilder is the way to go here.
    ice374, JazzaG and TheGreenGamerHD like this.
  5. Offline


    only thing that getOnlinePlayers() returns list of Player object, not strings.
    ice374 and desht like this.
  6. Offline


    If you dont like to use Stringbuilder and regexp, maybe try this:
    1. String playerlist = "";
    2. for (Player player : getServer().getOnlinePlayers()) {
    3. playerlist += playerlist.isEmpty() ? "" : ", " + player.getDisplayName();
    4. }
    ice374 likes this.
  7. Offline


    Oops :) Yeah, you're right.

    No, that is absolutely the worst way to do it.

    EDIT by Moderator: merged posts, please use the edit button instead of double posting.
    Last edited by a moderator: Jun 3, 2016
    ice374 likes this.
  8. Offline


    Thanks for the link, didnt thought that its that a big difference in performance, but now I know. Will check my own plugin, maybe StringBuilder will replace some things there :)
    ice374 and desht like this.
Thread Status:
Not open for further replies.

Share This Page