Home > Blockchain >  Foreach for nested list in Java
Foreach for nested list in Java

Time:06-17

I have hero dataset i want to show list with all heroes are durable is true and agile is true from this dataset

{
    "hero_code": 1,
    "hero_name": "Blood Seeker",
    "power": [
        {
            "skill": "Durable",
            "status": true
        },
        {
            "skill": "Agile",
            "status": true
        }
    ]
},
{
    "hero_code": 2,
    "hero_name": "Pudge",
    "power": [
        {
            "skill": "Durable",
            "status": true
        },
        {
            "skill": "Agile",
            "status": false
        }
    ]
},
{
    "hero_code": 3,
    "hero_name": "Necrophos",
    "power": [
        {
            "skill": "Durable",
            "status": true
        },
        {
            "skill": "Agile",
            "status": true
        }
    ]
}

this is what i do to achieve that

List<Hero> filteredList = new ArrayList<>;
data.getHeroList().forEach(hero-> {
hero.getpower().forEach(power-> {
    if (power.getSkill().contains("Durable") || power.getSkill().contains("Agile")) {
        if (power.getStatus() == true){
            filteredList.add(hero);
        }
    }
});
});

but why my filtered list end up with 6 data instead of 2 ? could anyone give me some insight ? Thanks

CodePudding user response:

Here's my attempt. Didn't check if it works.

List<Hero> filteredList = new ArrayList<>;
data.getHeroList().forEach(hero-> {
    boolean hasDurable = false;
    boolean hasAgile = false;
    hero.getpower().forEach(power-> {
        if (power.getSkill().contains("Durable") && power.getStatus()) {
            hasDurable = true;
        }
        if (power.getSkill().contains("Agile") && power.getStatus()) {
            hasAgile = true;
        }
    });
    if(hasDurable && hasAgile) {
        filteredList.add(hero);
    }
});

CodePudding user response:

You need to replace or condition with and (|| -> &) as per your question statement

  •  Tags:  
  • java
  • Related