views:

225

answers:

7

I have a issue with my java code. i asked the same question yesterday. I got answer but sorry it was my fault. My question is not clear.

I have code looks like this:

 for(i = 0; i < geo.getTargets().length ; i++ )
    {
        if(geo.getTargets(i).getTargetType().equalsIgnoreCase("ProximityTarget"))
        {
            final ProximityTarget prox = (ProximityTarget)geo.getTargets(i);
            prox.getGeoPoint().getLatitudeInMicroDegrees(); 
            prox.getGeoPoint().getLongitudeInMicroDegrees();
            prox.getRadiusDistanceUnits();
        }
    }

The above three method will give me some values.

I want these values to be place in this format:

circle:long:lat:radius | circle:long:lat:radius | .....

Can any one help me in fixing this code. I would like these value to be concatenated in a single string in order to insert it into my database field.

+1  A: 

The most basic way of doing Java string concatenation is to use the + operator. Set up:

String value = string1 + string2 + string3;

There are other ways to do it, but this simple case should handle your needs. For further information, look into StringBuilder.

justkt
+5  A: 

Try this:

StringBuilder sb = new StringBuilder();
for(i = 0; i < geo.getTargets().length ; i++ ){
  if(geo.getTargets(i).getTargetType().equalsIgnoreCase("ProximityTarget")){
    final ProximityTarget prox = (ProximityTarget)geo.getTargets(i);
    float longitude = prox.getGeoPoint().getLatitudeInMicroDegrees()); 
    float lat = prox.getGeoPoint().getLongitudeInMicroDegrees());
    float radius = prox.getRadiusDistanceUnits();

    if (sb.isEmpty()) {
        sb.append("circle:" + longitude + ":" + lat + ":" + radius);
    else {
        sb.append(" | circle:" + longitude + ":" + lat + ":" + radius);
    }
  }
}
String result = sb.toString();
Thierry-Dimitri Roy
Can also use sb.append("circle:").append(longitude).append(":").append... etc. - I believe this may be more performant than using "+" concatenator.
Lunivore
what is that? using a `StringBuilder` and the `+` together. Why not use just `+` without the `StringBuilder`? (or just the `StringBuilder` if you need that optimization)
Carlos Heuberger
This should all be broken up like Lunivore suggested. Don't mix the StringBuilder.append and + operators. StringBuilder offers optimizations and mixing them with + operators kind of defeats the purpose.
Erick Robertson
@Lunivore, @Carlos, @Erick, I disagree. @Lunivore : AFAIK in Java, this kind of + is implemented using a hidden StringBuilder anyway. @Carlos, @Erick: The optimization is not that significant on small strings. In this example, using + inside sb.append() is a good thing for readability at a place optimisation is not really required. Using StringBuilder for the global string is good for optimization at the place where it is useful. And there is no logical incompatibility at all in mixing + and StringBuilder this way (otherwise I'd say StringBuilder is too unsafe...)
@fred-hh I couldn't have said it better. I prefer StringBuilder for iteration and "+" where it's more readable.
Thierry-Dimitri Roy
@fred-hh Are you sure this code doesn't create a temporary StringBuilder, call the toString method on it and add this to your StringBuilder ?
Colin Hebert
@fred-hh A quick experiment confirms - you're right, '+' as used here appears to be more performant. 63ms vs 234ms for 10,000 iterations. Curious.
Lunivore
@Colin you're right, but that doesn't change my point.
+2  A: 
public String asString(ProximityTarget target) {
    StringBuilder sb = new StringBuilder("circle:");
    sb.append(target.getGeoPoint().getLatitudeInMicroDegrees()).append(":");
    sb.append(target.getGeoPoint().getLongitudeInMicroDegrees()).append(":");
    sb.append(target.getRadiusDistanceUnits());
    return sb.toString();
}

public void someMethod() {
    //...
    StringBuilder sb = new StringBuilder();
    for(i = 0; i < geo.getTargets().length ; i++ )
    {
        if(geo.getTargets(i).getTargetType().equalsIgnoreCase("ProximityTarget"))
        {
            final ProximityTarget prox = (ProximityTarget)geo.getTargets(i);

            if (!sb.isEmpty())
                sb.append("|");

            sb.append(asString(prox));
        }
    }
    String formattedString = sb.toString();

    //...
}
Yuri.Bulkin
A: 

Depends on the kind of environment you're on. If you don't need thread safety, use stringbuilder. The stringbuffer class provides the necessary synchronisation when needed.

Kurt Du Bois
+4  A: 

This is the basic way of doing what you asked for with String + operator.

  String result = "";
    for(i = 0; i < geo.getTargets().length ; i++ ){
      if(geo.getTargets(i).getTargetType().equalsIgnoreCase("ProximityTarget")){
        final ProximityTarget prox = (ProximityTarget)geo.getTargets(i);
        float longitude = prox.getGeoPoint().getLatitudeInMicroDegrees()); 
        float lat = prox.getGeoPoint().getLongitudeInMicroDegrees());
        float radius = prox.getRadiusDistanceUnits();

        if (!result.isEmpty()) {
            result += "|";
        }

        result += ("circle:" + longitude + ":" + lat + ":" + radius);
      }
    }

    return result;
The Elite Gentleman
For copyright notice, this source is a modified response from source code posted by @Thierry-Dimitri Roy.
The Elite Gentleman
No, don't use `+=` and `String` for building strings, that's `O(N^2)`. Use `StringBuilder` instead.
polygenelubricants
@polygenelubricants, true. There are solutions here that shows how to use StringBuilder, I was just showing alternative.
The Elite Gentleman
A: 

moreover, if it is possible to estimate the size of the concatenated string, you could use StringBuffer(int capacity)/StringBuilder(int capacity) to avoid resizing

codeplay
A: 

Additions to Thierry-Dimitri Roys response.

StringBuilder sb = new StringBuilder();
ProximityTarget prox;
float latitude;
float longitude;
float radius;

//Use for-each if you process all elements
for(Target target : geo.getTargets()){

  //Use literal string first to avoid NullPointerException
  if("ProximityTarget".equalsIgnoreCase(target.getTargetType())){
    prox        = (ProximityTarget)geo.getTargets(i);
    latitude    = prox.getGeoPoint().getLatitudeInMicroDegrees()); 
    longitude   = prox.getGeoPoint().getLongitudeInMicroDegrees());
    radius      = prox.getRadiusDistanceUnits();

    //Checking sb every loop is not a good practice.
    //Instead try removing first delimeter after for-loop
    sb.append("|circle:" + longitude + ":" + latitude + ":" + radius);
  } 
}

//AFAIK StringBuilder has no isEmpty Method.
//So use length method
if (sb.length() > 0){
    sb.deleteCharAt(0);
}

String result = sb.toString();  
krmby