2

Let's assume that I have a datastructure with n elements (0, 1, ... , n-1).

And assume these elements have some property I want to print (assume an int). And I want to print the datastructure on one line, with a delimiter (comma, space). So, the result would be something like this

13, 14, 15, 16, 17

What is the best way to add the comma and space (in Java)?

These are approaches I've taken:

  1. If the datastructure is Iterable, iterate from 0 to n-2 and append the delimiter to each of those, then print the last element.

  2. Loop through all elements and append everything to empty String (or Stringbuilder), then at the very end remove the last deliminator (hardcoded).

I feel like there's something better.

Edit: The question is unique. The 'possible duplicate' involves only printing, not messing with delimiters.

Edit2: Attempts as requested

// 1st approach
public void printStuff(ArrayList<Integer> input) {
    for (int i=0; i<input.size()-1; i++) {
        System.out.print(input.get(i) + ", ");
    }
    System.out.println(input.get(input.size()-1);
}

Another attempt

// 2nd approach
public void printStuff(ArrayList<Integer> input) {
    StringBuilder sb = new StringBuilder();
    for (int i=0; i<input.size(); i++) {
        sb.append(input.get(i)+", ");
    }
    sb.substring(0, input.size()-2);
    System.out.println(sb.toString());
}
jiaweizhang
  • 809
  • 1
  • 11
  • 28
  • 3
    Please post code for your attempts. – Andy Turner Oct 02 '15 at 14:11
  • If your list elements are custom objects, you can also alter their representation by overriding `Object#toString`. – Mena Oct 02 '15 at 14:13
  • Have a look at the code for Guava's `Joiner` class, see how it is implemented. Or `java.util.Arrays.toString`. – Andy Turner Oct 02 '15 at 14:13
  • 2
    Or the Java 8 [StringJoiner](https://docs.oracle.com/javase/8/docs/api/java/util/StringJoiner.html). – Keppil Oct 02 '15 at 14:14
  • 1
    Possible duplicate of [How to print out all the elements of a List in Java?](http://stackoverflow.com/questions/10168066/how-to-print-out-all-the-elements-of-a-list-in-java) – Alvaro Silvino Oct 02 '15 at 14:15
  • @AlvaroJoao It's literally a completely different question. The question you linked doesn't even address delimiters, simply printing on separate lines – jiaweizhang Oct 02 '15 at 15:10
  • 2
    it's amazing the triviality of problems one has to deal with in Java... – Erik Kaplun Oct 02 '15 at 19:12

5 Answers5

6

Java 8's streaming APIs finally provide an elegant, native, way of doing this without resorting to ugly if-else structures or using third parties.

Assuming you have a list of MyClass objects, and assuming MyClass has a getPropery() access method that returns an int, you could do something like this:

List<MyClass> list = ...;
String concatination = list.stream()
                           .map(p -> String.valueOf(p.getProperty()))
                           .collect(Collectors.joining(", "));
Mureinik
  • 297,002
  • 52
  • 306
  • 350
  • Awesome answer. Thanks! Do you have a specific online resource where I can read up more on this? – jiaweizhang Oct 02 '15 at 15:10
  • 1
    @jiaweizhang [Oracle's tutorials](https://docs.oracle.com/javase/tutorial/collections/streams/index.html) are pretty decent. – Mureinik Oct 02 '15 at 15:25
1

Using an iterator I would check whether there are any items left. If so, add a separator:

if (i.hasNext()) s.append(", ");
Richard Osseweyer
  • 1,693
  • 20
  • 25
1

Use some Java 8 Stream magic:

List<Integer> list = Arrays.asList(1, 2, 3) //just so we have a list to work on
String result = list.stream()
        .map(it -> it.toString())
        .collect(Collectors.joining(", "))
Tobias Kremer
  • 1,531
  • 2
  • 15
  • 21
0

You could use a framework, like this:

https://google-collections.googlecode.com/svn/trunk/javadoc/com/google/common/base/Joiner.html

Joiner.on(",").join(list)

0

You could remove the first element, add it to your String and add , <string> to it:

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

// add elements

StringBuilder buffer = new StringBuilder();
buffer.append(lst.remove(0));

for(String s : lst) {
    buffer.append(", ").append(s);
}
Joshua
  • 2,932
  • 2
  • 24
  • 40
  • This is the same thing as I did for attempt 2 though backwards though it does take care of the hardcoded endpiece. – jiaweizhang Oct 02 '15 at 22:28