如何使用Java流过滤地图地图
来源:爱站网时间:2021-09-16编辑:网友分享
如何使用java流过滤地图。我可以使用双循环来做到这一点,但我认为这样做效率不高。公共类MapUsage {静态Map
> ...
问题描述
如何使用java流过滤地图。我可以使用双循环来做到这一点,但我认为这样做效率不高。
public class MapUsage {
static Map> parentMap = new HashMap();
static Map userRole = new HashMap();
public static void main(String ... args){
initializeData();
displayMapForUser("user1", parentMap);
// printMap(parentMap);
}
private static void displayMapForUser(String user1, Map> parentMap) {
Integer role = new Integer(userRole.get(user1));
Map> userMap = new HashMap();
Map childMap = new HashMap();
for(Map.Entry> entry : parentMap.entrySet()){
for(Map.Entry entry1: entry.getValue().entrySet()){
if(entry1.getKey().equals(role))
childMap.put(entry1.getKey(), entry1.getValue());
}
userMap.put(entry.getKey(), childMap);
}
printMap(userMap);
}
private static void printMap(Map> parentMap) {
for(Map.Entry > entry: parentMap.entrySet()){
System.out.println("key: "+entry.getKey());
System.out.println("value: "+entry.getValue());
}
}
private static void initializeData() {
Map childMap1 = new HashMap();
Map childMap2 = new HashMap();
userRole.put("user1", "1");
userRole.put("user2", "2");
userRole.put("user3", "3");
userRole.put("user4", "4");
childMap1.put(1, "one");
childMap1.put(2, "two");
childMap1.put(3, "three");
childMap1.put(4, "four");
parentMap.put(1, childMap1);
childMap2.put(1, "one");
childMap2.put(2, "two");
childMap2.put(3, "three");
parentMap.put(2, childMap2);
}
}
输出为:
key: 1
value: {1=one}
key: 2
value: {1=one}
思路:
您可以在此处使用Collectors.toMap
: