2

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.

5
  • You might want to wrap your code parts in a code block so it's more readable. Click "edit" under your post, select the code text with your mouse, then click the button that looks like a 3 by 2 block of 1s and 0s (should be the 5th icon from the left, just after the quotation mark icon and just before the picture icon.) Commented Aug 23, 2010 at 12:10
  • @Stephen: Those instructions confused me more than they'd help I think ;-) Commented Aug 23, 2010 at 12:13
  • @Joey: Perhaps, but it just seems like 90% of the time some poor sod with editing rights has to come along, hit edit, select the text and click the button. For some reason people never seem to explore formatting options even when they must be able to see that their post doesn't look... 'right'. Oh well. Commented Aug 23, 2010 at 12:21
  • LOL. (For the sake of having 15 characters or more). Commented Aug 23, 2010 at 12:55
  • 1
    I'm not sure if concatenating multiple records into one long string to be put into the database is a good idea. It would make queries really awkward. Commented Aug 23, 2010 at 13:27

7 Answers 7

5

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();
Sign up to request clarification or add additional context in comments.

7 Comments

Can also use sb.append("circle:").append(longitude).append(":").append... etc. - I believe this may be more performant than using "+" concatenator.
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)
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.
@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.
|
4

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;

3 Comments

For copyright notice, this source is a modified response from source code posted by @Thierry-Dimitri Roy.
No, don't use += and String for building strings, that's O(N^2). Use StringBuilder instead.
@polygenelubricants, true. There are solutions here that shows how to use StringBuilder, I was just showing alternative.
2
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();

    //...
}

Comments

1

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.

Comments

0

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.

Comments

0

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

Comments

0

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();  

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.