Getting players names from an ArrayList

Discussion in 'Spigot Plugin Development' started by TimeVisualSales, May 16, 2015.

  1. Hi there, I was wondering how I would broadcast a message on the server but the message contains all the players names that are in a certain ArrayList. Does anyone know how to do this?
  2. Code (Text):
    Bukkit.broadcastMessage("Something something for these players: " + StringUtils.join(list,", "));
    Where list is the list containing player names.
  3. What should I import for the StringUtils?
  4. it's from Apache Commons
  5. Code (Text):
    ArrayList<Player> players = new ArrayList<>(); //this arraylist will contain the players you need
    String allplayers = "";
    for(Player x: players){
        allplayers += x.getName() + ", ";
    Bukkit.broadcastMessage(allplayers.substring(0,allplayers.length-1)); //we need the .substring to remove the last ',' in the string.

    this will work
  6. And like any language in which strings are immuatable, this is a terrible idea. Use a StringBuilder for java, which is what StringUtils does.

    In addition, StringUtils is a single line vs. 4 from there.
    • Agree Agree x 1
  7. Didn't even think about that haha. I was in the programming competition mindset of "Pick the shortest obvious path that comes to you, follow it" when the problem is simple. I guess if you were to have a large list of players that would take of exponentially more memory that a StringBuilder. But then again a few shorts here and there never hurt anyone.
  8. Code (Text):

    StringBuilder sb = new StringBuilder();
    for(String string : strings) {
    sb.append(string).append(", ");
    • Agree Agree x 1