Java8:使用过滤/谓词结合析取处理布尔Map对比需求
Hey there! Let's break down how to solve this problem using Java 8's functional features to get the exact count you need.
Step 1: Define Our Test Maps
First, let's create the two maps exactly as you described—no surprises here:
import java.util.Map; import java.util.HashMap; import java.util.function.Predicate; public class MapTrueCountComparison { public static void main(String[] args) { // Initialize map1 with specified entries Map<String, Boolean> map1 = new HashMap<>(); map1.put("i1", true); map1.put("i2", true); map1.put("i3", false); map1.put("i4", true); // Initialize map2 with specified entries Map<String, Boolean> map2 = new HashMap<>(); map2.put("i1", true); map2.put("i2", false); map2.put("i3", true); map2.put("i5", true);
Step 2: Create Predicates for Our Conditions
We need two core boolean checks, wrapped into reusable predicates:
- Predicate A: The entry exists in both maps, map1's value is
true, and map2's value isfalse - Predicate B: The entry only exists in map1, and map1's value is
true
Then we'll use disjunction (logical OR, via Predicate.or()) to combine these two—since we want to count entries that match either condition.
// Predicate for cross-map matches where map1 is true and map2 is false Predicate<Map.Entry<String, Boolean>> map1TrueMap2False = entry -> entry.getValue() && Boolean.FALSE.equals(map2.get(entry.getKey())); // Predicate for entries unique to map1 with a true value Predicate<Map.Entry<String, Boolean>> onlyInMap1AndTrue = entry -> entry.getValue() && !map2.containsKey(entry.getKey()); // Combine predicates using disjunction (logical OR) Predicate<Map.Entry<String, Boolean>> combinedCondition = map1TrueMap2False.or(onlyInMap1AndTrue);
Step 3: Filter and Count Matching Entries
Now we'll stream over map1's entries, apply our combined predicate to filter matches, and count the result:
// Calculate the final count long map1TrueMoreThanMap2True = map1.entrySet() .stream() .filter(combinedCondition) .count(); // Print the result (should output 2) System.out.println("map1TrueMoreThanMap2True = " + map1TrueMoreThanMap2True); } }
Why This Works
Let's verify against your sample data:
- Matching Predicate A: Entry
("i2", true)→ map2 has "i2" with valuefalse→ counts - Matching Predicate B: Entry
("i4", true)→ map2 doesn't have "i4" → counts - Total: 2, which is exactly the expected result!
We used Java 8's stream API for filtering, predicates for clean reusable logic, and Predicate.or() to implement the disjunction (OR) operation between our two conditions—perfectly aligning with your requirements.
内容的提问来源于stack exchange,提问作者ojas

