如何用Groovy从Map中获取并筛选年龄>35的人员列表?
Hey there! Let’s work through this problem step by step. I’ll start with a realistic sample scenario matching your use case, show you the correct Groovy code to get the filtered list, and also cover common pitfalls that might have caused your error.
1. Sample Data Setup
First, let’s define a sample map and target ID list that mirrors your scenario:
// Sample map: Keys are person IDs, values are person objects with id/name/age def peopleMap = [ 1: [id: 1, name: "Alice", age: 32], 2: [id: 2, name: "Bob", age: 40], 3: [id: 3, name: "Charlie", age: 38], 4: [id: 4, name: "Diana", age: 30], 5: [id: 5, name: "Eve", age: 45] ] // Your list of target IDs to retrieve def targetIds = [2, 3, 5, 6] // Note: ID 6 doesn't exist in the map (common edge case)
2. Correct Filtering Approach
Here’s the clean, safe way to fetch and filter your data:
// Step 1: Fetch all people from the map using target IDs, skipping non-existent entries def targetPeople = targetIds.collect { peopleMap[it] }.findAll { it != null } // Step 2: Filter to keep only people with age > 35 def filteredPeople = targetPeople.findAll { it.age > 35 } // Output the result println(filteredPeople) // Expected output: [[id:2, name:Bob, age:40], [id:3, name:Charlie, age:38], [id:5, name:Eve, age:45]]
3. Common Error Causes & Fixes
If you ran into errors, here are the most likely issues and how to fix them:
- NullPointerException: This happens if your target ID list includes IDs that don’t exist in the map (like ID 6 in our sample). The fix is to add the
findAll { it != null }step to skip null entries before accessing theageproperty. - Type Mismatch Error: If your
agevalue is stored as a string instead of a number, comparing it to 35 will throw an error. Fix this by converting it to a numeric type first:def filteredPeople = targetPeople.findAll { (it.age as Integer) > 35 } - Incorrect Map Structure: If your map doesn’t use IDs as keys (e.g., it has a top-level key like
peoplethat holds the full list), adjust the code to first extract the list, then filter by both target IDs and age:// Example alternative map structure def dataMap = [ people: [ [id:1, name:"Alice", age:32], [id:2, name:"Bob", age:40], [id:3, name:"Charlie", age:38] ] ] def filtered = dataMap.people.findAll { targetIds.contains(it.id) && it.age > 35 }
内容的提问来源于stack exchange,提问作者p_nair
相关产品推荐
相关产品推荐

