Home > front end >  Iterate through a list and get the id of the person whose status is tagged
Iterate through a list and get the id of the person whose status is tagged

Time:12-06

I want to loop through this json and stop where the status is tagged, as well as get the value of that id. Here is what I've done so far. Can someone help me figure out how to do this? By this method, I'm able to stop the loop and return true where the status is "tagged," but the problem is that I also want to return the value of Id from here where the status is "tagged."

json:

{
"message": "Multiple_number",
"listOfId": [
{
    "Id": "7895953453",
    "aliasName": "",
    "status": "Active"
},
{
    "Id": "9045451400",
    "aliasName": "",
    "status": "tagged"
},
{
    "Id": "8923688789",
    "aliasName": "",
    "status": "Pending"
}
],
  "status": "FAILURE"
}

Code:

HashMap<String, Object> json = parser.object();
if (json.containsKey("listOfId")) {
    ObjectMapper objectMapper = new ObjectMapper();
    StatusResponseCO mobileDcResponseDto = 
    objectMapper.readValue(responseEntity, StatusResponseCO.class);
    List<StatusResponseSubCO> statusResponseCOS = mobileDcResponseDto.getListOfId();
    Map<String, Long> counting = statusResponseCOS.stream().collect(
        Collectors.groupingBy(StatusResponseSubCO::getStatus, Collectors.counting()));
    System.out.println(counting);
    for (Map.Entry<String, Long> entry : counting.entrySet()) {
        String status = entry.getKey();
        if ("Tagged".equals(status)) {
            return true;
        }
    }

StatusResponseCO.java

public class StatusResponseCO {
    private List<StatusResponseSubCO> listOfId;
}

StatusResponseSubCO.java

public class StatusResponseSubCO {
    private String Id;
    private String status;
}

CodePudding user response:

So I made a runnable example for you (that includes the full source as well). The gist of it is simply passing the deserialized list to this method:

public static List<StatusResponseSubCO> findTagged(List<StatusResponseSubCO> list){
    return list.stream().filter(sub -> 
        sub.status.equals("tagged"))
            .collect(Collectors.toUnmodifiableList());
}

You loop through the list (can also do this with an old school for loop), filtering out everything that does not match the predicate and then collect the result and turn it into a list;

If you then are 100% that there can ever only be a single match in the original list, you can of course just add a .get(0) to the resulting list to get the single StatusResponseSubCO instance and through that get the id.

There are a bunch of improvements you could do, of course:

  • avoid direct string comparisons and de-serialize directly into an enum
  • use a more modern Java (we are on Java 19!) - you can always compile to an earlier target runtime if needed
  • use record types (Java 14)
  • use Streams.toList() to simplify a bit (Java 16)

CodePudding user response:

Your code makes the assumption that there will be a single record that is 'tagged' so I'll make the same assumption. You have already converted the JSON to the datatype and have the List of records when you make this call.

List<StatusResponseSubCO> statusResponseCOS = mobileDcResponseDto.getListOfId();

So you should be able to iterate this List, find the record that has status 'tagged' and return the ID of that record. The following examples assume that not finding a matching record is a bad state and throw an Exception of some sort. You could return null if that is reasonable.

Using the Stream API.

Optional<String> id = statusResponseCOS.stream()
    .findAny(r -> "Tagged".equals(r.getStatus()))
    .map(r -> r.getId());
if (id.isPresent()) { 
  return id.get();
}
throw SomeBadStateOrWhateverException("No sub record is Tagged");

You can also use a regular for-loop

for (StatusResponseSubCO r: statusResponseCOS) {
  if ("Tagged".equals(r.getStatus()) {
    return r.getId();
  }
}
throw SomeBadStateOrWhateverException("No sub record is Tagged");
  • Related