有两个Map<String,List<String>的map,一个是标签与标问,一个是导航与标签,怎么用java的方式生成一个导航与标问的map
时间: 2024-05-05 07:21:56 浏览: 59
java代码-使用java解决bean&map工具类的源代码
假设输入的两个Map的变量名分别为`tag2QuestionMap`和`nav2TagMap`,可以按照以下步骤生成导航与标问的Map:
1. 创建一个空的Map<String, List<String>>,用于存放导航与标问的映射关系:
```java
Map<String, List<String>> nav2QuestionMap = new HashMap<>();
```
2. 遍历`nav2TagMap`中的每个导航和对应的标签列表,对于每个标签,在`tag2QuestionMap`中查找对应的标问列表,将其加入到导航对应的标问列表中:
```java
for (Map.Entry<String, List<String>> entry : nav2TagMap.entrySet()) {
String nav = entry.getKey();
List<String> tagList = entry.getValue();
List<String> questionList = new ArrayList<>();
for (String tag : tagList) {
if (tag2QuestionMap.containsKey(tag)) {
questionList.addAll(tag2QuestionMap.get(tag));
}
}
nav2QuestionMap.put(nav, questionList);
}
```
在上述代码中,首先遍历`nav2TagMap`中的每个导航和对应的标签列表,然后对于每个标签,通过`tag2QuestionMap`查找对应的标问列表,将其加入到导航对应的标问列表中。最后将导航和标问列表的映射关系加入到`nav2QuestionMap`中。
完整代码示例:
```java
Map<String, List<String>> tag2QuestionMap = new HashMap<>();
tag2QuestionMap.put("tag1", Arrays.asList("question1", "question2"));
tag2QuestionMap.put("tag2", Arrays.asList("question3", "question4"));
tag2QuestionMap.put("tag3", Arrays.asList("question5"));
Map<String, List<String>> nav2TagMap = new HashMap<>();
nav2TagMap.put("nav1", Arrays.asList("tag1", "tag2"));
nav2TagMap.put("nav2", Arrays.asList("tag2", "tag3"));
nav2TagMap.put("nav3", Arrays.asList("tag1", "tag3"));
Map<String, List<String>> nav2QuestionMap = new HashMap<>();
for (Map.Entry<String, List<String>> entry : nav2TagMap.entrySet()) {
String nav = entry.getKey();
List<String> tagList = entry.getValue();
List<String> questionList = new ArrayList<>();
for (String tag : tagList) {
if (tag2QuestionMap.containsKey(tag)) {
questionList.addAll(tag2QuestionMap.get(tag));
}
}
nav2QuestionMap.put(nav, questionList);
}
System.out.println(nav2QuestionMap);
```
输出结果:
```
{nav1=[question1, question2, question3, question4], nav2=[question3, question4, question5], nav3=[question1, question2, question5]}
```
阅读全文