The code below works:

public class concat {
    public static void main(String[] args){
         String[] filters = {"A","B","C","A","K","C"};
         String[] values = {"1","2","3","4","5","6"};  
         String a = "";

         for(int i=0;i<filters.length;i++){
             String temp = filters[i];
             for(int j=0;j<filters.length;j++){
                 if(filters[j].equalsIgnoreCase(temp)){ 
                     a += values[j] + " ";
                     values[j]="";
                 }
             }
             if(a.trim().length()!=0){
                 System.out.println(temp + " [" + a + "]");
             }
             a = "";
         }
    }
}

It produces the following results:

A [1 4 ]
B [2 ]
C [3 6 ]
K [5 ]

However I intend to achieve the following results:

A [1,4]
B [2]
C [3,6]
K [5]

How can I accomplish it with my code. Your help is kindly appreciated.

A quick fix would be... (not very efficient)

// change from this line
a += values[j] + " ";

// to
if (!a.isEmpty()) { a += ","; }
a += values[j];
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.