简体   繁体   中英

Java Using Multiple predicate for anyMatch

I am having a List of HashMap ie List<Map<String, Object>> result . I want to check if some key value is present on this list or not.

For Example:

Name      Count 
Marvel    10
DC         0  

I want that my list of map should contain at least one entry for the above table for that I am using anyMatch

Assert.assertTrue(
result.stream().anyMatch(
ag -> ( "Marvel".equals(ag.get("Name")) &&  10==(int)ag.get("Count"))
));

How can I use multiple Predicates ? I can have a list of 1000 HashMap , I just want to check if any two Hash-map from my list contains those two entries.

Your data structure seems wrong for a start. A List<Map<String, Object>> , where each map represents a row and has only one key and one value? You just need a Map<String, Integer> . The string is the name, the integer is the count. Remember to give it a meaningful name, eg comicUniverseToSuperheroFrequency .

With that said, Predicate has an and method which you can use to chain conditions together. It might look something like this:

public static void main(String[] args)
{
    Map<String, Integer> comicUniverseToSuperheroFrequency = /*something*/;

    boolean isMarvelCountTen = comicUniverseToSuperheroFrequency.entrySet().stream()
        .anyMatch(row -> isMarvel().and(isTen()).test(row));
}

private static Predicate<Map.Entry<String, Integer>> isMarvel()
{
    return row -> "Marvel".equals(row.getKey());
}

private static Predicate<Map.Entry<String, Integer>> isTen()
{
    return row -> row.getValue() == 10;
}

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