The_learning_guy
The_learning_guy

Reputation: 51

Java Using Multiple predicate for anyMatch

I am having a List of HashMap i.e 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.

Upvotes: 4

Views: 7433

Answers (1)

Michael
Michael

Reputation: 44150

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, e.g. 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;
}

Upvotes: 2

Related Questions