2

I am having a Vector<String> containing some items. I want to search those items in database.

For that purpose I need to make a String consisting of comma separated items out of that Vector so that I can pass it to SQL Query.

I am doing something like this.

 StringBuilder list = new StringBuilder("");
        for (String items : itemList) {
          if(its last element then) //How to check here  
            list.append(items);
          else       
            list.append(items+",");
       }

but that will return me the output like "item1,item2,item3,"

where as I want to omit the last comma (,) in case if it is last element of Vector.

I have checked Vector API and found this method lastElement() (which returns last element not boolean).

How can I check it in the loop or is there any smarter/efficient way to do it?

Tom
  • 16,842
  • 17
  • 45
  • 54
Sajjad
  • 853
  • 2
  • 15
  • 32
  • if(items.equals(vector.lastElement()){\\dont append comma here} – user Dec 20 '14 at 12:31
  • If you can use Java 8, then look for [`String.join()`](http://docs.oracle.com/javase/8/docs/api/java/lang/String.html#join-java.lang.CharSequence-java.lang.CharSequence...-). – Tom Dec 20 '14 at 12:33
  • @user instead of comparing each element in for loop with string like aaaaaa in case of vector like {a, aa, aaaa, aaaaaa} will not be efficient. – SMA Dec 20 '14 at 12:36

7 Answers7

2

This is a possible duplicate of Java: function for arrays like PHP's join()?

Don't reinvent the wheel! This has been done many many times, unit tested and maintained. so use them, don't make your own.

You can use Apache Commons StringUtils and use the join method on Iterable (which Vector is)

StringUtils.join(itemList, ", ")

Also, as pointed out by Tom in the comments of your question, in Java 8 you can use String.join()

Community
  • 1
  • 1
Mark Fisher
  • 9,838
  • 3
  • 32
  • 38
2

I would go with the String.join approach.

final List<String> itemList = Arrays.asList("item1", "item2", "item3");
final String commaSeparated = String.join(",", itemList);
System.out.println(commaSeparated); // -> item1,item2,item3

A nice and clean solution. Only available for Java 8.

wassgren
  • 18,651
  • 6
  • 63
  • 77
1

Have a look at libraries like Google Guava

Joiner.on(",").useForNull("null").join(itemList)
Christian Dietrich
  • 11,778
  • 4
  • 24
  • 32
1

Since you're using a StringBuilder, it's easier to just delete the last comma:

    StringBuilder list = new StringBuilder("");
    for (String items : itemList) {
        list.append(items).append(',');
    }
    if ( list.length() > 0 ) {
        list.setLength(list.length() - 1 );
    }
RealSkeptic
  • 33,993
  • 7
  • 53
  • 79
0

Change your loop as below:

for (int i=0; i<itemList.size(); i++) {
  list.append(itemList.get(i));
  if(i != itemList.size() - 1) {
      list.append(",");           
  } 

Internally vector uses array and you are accessing element by index now instead of using advance for each loop.

SMA
  • 36,381
  • 8
  • 49
  • 73
0

There are several third party libraries that do the heavy lifting for you, like Apache Commons Lang's StringUtils:

String list = StringUtils.join(items, ',');

If you absolutely must do this yourself, I'd start with the first element and append a comma and an element for each succeeding element:

StringBuilder list = new StringBuilder();
Iterator<String> iter = items.iterator();

if (iter.hasNext()) {
    // Special treatment for the first item
    list.append(iter.next());

    // The rest of the items
    while (iter.hasNext()) {
        list.append(',').append(iter.next());
    }
}
Mureinik
  • 297,002
  • 52
  • 306
  • 350
0

Simply use,

StringUtils.join(itemList, ", ");
  • 2
    this solution has already been suggested twice, and in both other examples they actually link the site you can get that util from. – Mark Fisher Dec 20 '14 at 12:52