Solved List to String

Discussion in 'Plugin Development' started by Pink__Slime, Jun 7, 2013.

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

    Pink__Slime

    Hey community, I'm trying to send a player a list but I dislike how it's sent like this:
    Code:
    List: [item1,item2,item3]
    Is there anyway to get it so it will send like this?:
    Code:
    List: item1, item2, item3
    (The commas after the list item would be nice but aren't necessary).
     
  2. Offline

    skore87

    Here you go. A simple little method to make your list look like you're asking. I wrote it without aid of the IDE so I may have written something wrong like wrong method name for the size of a list.

    Code:
    public static String listToString(List<String> list){
        StringBuilder sb = new StringBuilder();
        if (list != null && list.size() > 1){
            sb.append(list.get(0));
            for (int i = 1; i < list.size(); i++){
                sb.append(", " + list.get(i));
            }
        }else if(list != null && (list.size() == 1)){
            sb.append(list.get(0));
        }
        return sb.toString();
    }
     
    Pink__Slime likes this.
  3. Offline

    Pink__Slime

    skore87
    Thanks! That's perfect.
     
  4. Offline

    lycano

    And a one-liner (Line one is to fill your array for the example so it doesn't count xD)

    Code:
    List<String> myStringList = Arrays.asList("item1", "item2", "item3");
     
    String myString = myStringList.toString().substring(1, myStringList.toString().length() - 1);
    
    If you use myStringList.toString() it will give you "[item1, item2, item3]" a comma seperated list with one space after the delimiter comma.

    To get rid of those just use String.substring(int beginIndex, int endIndex) to extract the middle which is in this case start at index one which is the "i" and end at (end - 1) "3" (myStringList.toString().length() - 1)
     
  5. Offline

    zack6849

    or you could use regex :D

    Code:
    yourlist.toString().replaceAll("[\\['']|['\\]'']", "");
    
     
  6. Offline

    lycano

    Haha nice! zack6849 ^.^ (I ignored the comma after toString() cause i know what you mean xD)
     
  7. Offline

    zack6849

Thread Status:
Not open for further replies.

Share This Page