views:

64

answers:

3

Hi,

I have array of ValueA and ValueB(int type) . I am reading each value from array using a for loop. I want to concatenate all there values in a single String. these value should be in the form of like these

ValueA1":"valueB1"|"ValueA2":"valueB2"|"ValueA3":"valueB3"|"ValueA4":"valueB4"|"....  

I want this in Java, please can some ne help me with code..

+2  A: 

You could try something like this

int[] valueA = methodWhichFillsA();
int[] valueB = methodWhichFillsB();
StringBuilder sb = new StringBuilder();
int maxSize = Math.max(valueA.length, valueB.length);
for(int i = 0; i < maxSize; i++){
    if(i > 0)
        sb.append("|");

    if(i < valueA.length)
        sb.append(valueA[i]);

    sb.append(":");

    if(i < valueB.length)
        sb.append(valueB[i]);
}
System.out.println(sb.toString());

This will evaluate the size of the biggest array between valueA and valueB, loop on this size. If the element exists it's printed. The first if is used to add the separator, if it's the first iteration no need for a "|"

Colin Hebert
Thanks for the reply. You are the man...
Salman
+1  A: 

Assuming the arrays are of different size, this solution will zip them together up until the end of the shorter array:

StringBuilder sb = new StringBuilder();
for(int i = 0; i < Math.min(arr1.length, arr2.length); i++){
    sb.append( arr1[i] ).append("\":\"").append( arr2[i] ).append("\"|\"");
}
System.out.println(sb.toString());
seanizer
both the arrays are having equal lengths.. Thank u seanizer for ur answer
Salman
then how about accepting one of the answers?
seanizer
+1  A: 

Just a different way of doing it, this uses Guava

private String test(int[] a, int[] b) {

    List<Integer> al = Lists.newArrayList();
    List<Integer> bl = Lists.newArrayList();
    for (Integer ai : a) {
        al.add(ai);
    }
    for (Integer bi : b) {
        bl.add(bi);
    }

    List<String> sets = Lists.newArrayList();
    Iterator<Integer> itera = al.iterator();
    Iterator<Integer> iterb = bl.iterator();
    while(itera.hasNext() && iterb.hasNext()) {
        sets.add(itera.next()+":"+iterb.next());
    }

    return Joiner.on("|").join(sets);

}

I was surprised to find no primitive array to list methods. If you can think of an elegant way to do that besides pulling it out into another method, the this code could be made cleaner.

BjornS