简体   繁体   中英

How to do this list iteration in java?

I have a list say,

"temp" : [{
              "value" : "24.6",
              "name" : "sellPrice"
            }, {
              "value" : "N",
              "name" : "IsAvail"
            }, {
              "value" : "http://my.com/prdurl/480389",
              "name" : "pd_URL"
            }

        }]

I am iterating over that to find IsAvail==N,

if (("IsAvail".equalsIgnoreCase(temp.get(i).getName().toString()))&& ("N".equalsIgnoreCase(temp.get(i).getValue().toString()))) {


 // Now here i want to print product url                                                                   
                    }

the iteration should continue inside to find the value?? I cant change the structure.

By analyzing your iteration, I would suppose you have a sort of XML attributes of nodes. A list o 'temp' on which each temp object, have those 3 attributes ( sellPrice , IsAvail and pd_URL ), and you want to get the pd_URL of the temps that match IsAvail==N .

Lets supose:

class Temp {
 Attribute[] attributes;
}
class Attribute{
 String name, value;
}

With the respective encapsulation.

you could iterate a list of Temp like this:

Temp[] temps = ...;
for( Temp t : temps ){
   String pd_URL="";
   boolean isAvail = false;
   for( Attribute att : t.getAttributes() ){
      if( "IsAvail".equalsIgnoreCase(att.getName()) ){
         if( "N".equalsIgnoreCase(att.getValue()) )
            isAvail==true;
         else break;
      } else if( "pd_URL".equalsIgnoreCase(att.getName()) ){
         pd_URL==att.getValue();
         if( isAvail ) break;
      }
   }
   if( isAvail ){
      System.out.println( "Temp with pd_URL: "+pd_URL+" has IsAvail == N" );
   }
}

It's pretty difficult to understand what you are asking given you don't supply the Java structure that this information is stored in. Assuming the structure looks something like:

Map<String, List<KeyValuePair>> nameValuesMap;

and what you actually want to do is to return keys that have a key-value pair with the criteria you give (big assumption), then you can do that with:

nameValuesMap.keySet().stream()
    .filter(name -> nameValuesMap.get(name).stream()
        .filter(keyValue -> keyValue.matches("IsAvail", "N"))
        .findAny().isPresent())
    ...

That's assuming your KeyValuePair class implements a matches predicate.

This code generates a stream which could then be collected into a list, iterated using forEach or whatever else you want to do.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM