0

I have the below three elements :

play_full_NAME=556677

pause_full_NAME=9922

stop_full_NAME=112233

A string "abc" returns all the above three elements one by one from a particular piece of code.

I am trying to add all three elements in a list separated by a colon ":"

Sample output :

play_full_NAME=556677:pause_full_NAME=9922:stop_full_NAME=112233

My attempt:

List<String> list = new ArrayList<String>();

list.join(":",abc)

Please help with a better way to handle this.

JAne
  • 97
  • 1
  • 10
  • 2
    _A string "abc" returns all the above three elements one by one_ — What does this mean? – khelwood Apr 23 '18 at 10:50
  • 1
    A better way? Your current attempt won't even compile. – Mark Rotteveel Apr 23 '18 at 10:52
  • @khelwood . I am running a loop which returns the elements one by one.My aim is to store them in a list where each element gets separated by a colon ":" – JAne Apr 23 '18 at 10:52
  • @Thanks for the response. I am searching for a way to store them in a list where each element gets separated by a colon ":" – JAne Apr 23 '18 at 10:53
  • Can I ask why do you need to add a `String` ":"` between each instance in that `List` ? Seems an odd requirements to be honest. If this is to print the list later. Simply add the `:` when you print the `List` between each element, not in the list itself. – AxelH Apr 23 '18 at 10:53
  • Lists don't store separators. The output would depend on the code that gives an output? I may be confused. – Xyexs Apr 23 '18 at 10:54
  • Why would you think the `list.add(":", abc)` works? Did you check the [documentation](https://docs.oracle.com/javase/10/docs/api/java/util/ArrayList.html)? There is no such method in the class. – Zabuzard Apr 23 '18 at 10:56

3 Answers3

12

Your understanding about List is little flawed. Comma is only printed for representation purposes.

To join strings with colon, you can do the following

List<String> list = Arrays.asList("play_full_NAME=556677", 
                                  "pause_full_NAME=9922", 
                                  "stop_full_NAME=112233");

String joinedString = String.join(":", list);
RubioRic
  • 2,442
  • 4
  • 28
  • 35
krisnik
  • 1,406
  • 11
  • 18
  • thanks for the response. But the value of the three elements is not static.Its a dynamic value.So cant hard code the value. I have already looked at : https://stackoverflow.com/questions/13395114/how-to-initialize-liststring-object-in-java – JAne Apr 23 '18 at 10:59
  • 1
    Yes. This will work for any dynamic list. Can you please share in which way you are expecting your input? – krisnik Apr 23 '18 at 11:05
  • 1
    The intersting part is the [`String.join(CharSequence delimiter, Iterable extends CharSequence> elements)`](https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#join-java.lang.CharSequence-java.lang.Iterable-) method @Jane. This could use some explanations but this is a good answer. – AxelH Apr 23 '18 at 11:06
  • 1
    Thanks for the effort !! – JAne Apr 24 '18 at 09:26
3

Did you really understood the List well?

In fact, there is no separator, each item / value is stored as different "object".

So you have some amount of independent values- Strings in this case, what can you see on screenshot bellow, or if you will do System.out.println(someList); it will call override of method toString() which is inherited from Object class , which is root parent class of all classes in Java.

enter image description here

So its absolutely nonsense to add some split character between each items in List, they are split already, you can access each item by get(int position) method.

So if you want to print each item of list "by yourself", can be done like follows:

for (int i = 0; i < someList.size(); i++) {
    System.out.println(i + " = " + someList.get(i));    
}
/* output will be 
   1 = 1 item
   2 = 2 item
   3 = 3 item
   4 = 4 item
*/

If you want to implement custom method for printing "your list" then you can extend eg. ArrayList class and override toString method, but better and more trivial approach will be prepare some method in some utils to get formatted String output with context of List- eg. (notice there will be ; after last element)

public static String getFormatStringFromList(ArrayList<String> data) {
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < data.size(); i++) {
        sb.append(data.get(i) + ";");   
    }

    return sb.toString();
    //eg. 0 item;1 item;2 item;3 item;4 item;
}

To avoid last separator you can do eg. simple check

public static String getFormatStringFromListWitoutLastSeparator(List<String> someList) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < someList.size(); i++) {
            sb.append(someList.get(i));
            if(i < someList.size() -1) {
                 sb.append(";");
            }
        }

        return sb.toString();
        //0 item;1 item;2 item;3 item;4 item
        /*
           someList[0] = 0 item
           someList[1] = ;
           someList[2] = 1 item
           someList[3] = ;
           {etc..}
        */
    }

The best approach to get String from list will be like @krisnik advised:

String joinedString = String.join(":", list);

xxxvodnikxxx
  • 1,270
  • 2
  • 18
  • 37
  • 1
    Good explanation (you should add the output for the first code) but check [krisnik](https://stackoverflow.com/a/49979321/4391450) to see how to correclty add a separator. Your solution adds one to many separator by the way. – AxelH Apr 23 '18 at 11:13
  • @AxelH hey, thanks, I added some more clues :) And yes, you are also correct, this is working , but totally not the best approach, just for demonstration to understand – xxxvodnikxxx Apr 23 '18 at 11:18
  • 1
    I personally prefer to remove the last character at the end with `sb.setLength(sb.length() - 1)` to remove the last character. That allow me to remove the condition in the loop ;) Just need to check if there is at least one item in the list (at the start). – AxelH Apr 23 '18 at 11:20
  • hehe :D many ways, but for sure `setLength` will be more effective – xxxvodnikxxx Apr 23 '18 at 11:21
  • 1
    Thanks a lot for helping !! – JAne Apr 24 '18 at 08:43
  • @JAne check also @krisnik solution, its better for creating separated string from `Array` or `List` – xxxvodnikxxx Apr 24 '18 at 09:07
1

You would need to add the colon elements separately if you want them to be within your list.

For example:

List<String> list = new ArrayList<String>();

list.add(abc);
list.add(":");
list.add(def);
list.add(":");

and so on.

I would recommend against this, however, as you can simply format the output string using String.format or a StringBuilder when you need it.

Austin Schaefer
  • 695
  • 5
  • 19