您可以通过Map<String, Map<String, Integer> 来做到这一点。
- 外图的关键是天气(
sunny、rainy等)
- 该值是另一个映射,其中包含每个可能的值(
yes、no、maybe...)以及该值出现的次数。
像这样合并两个列表:
public static Map<String, Map<String, Integer>> count(List<String> weathers, List<String> answers) {
//weathers olds the strings 'sunny', 'rainy', 'sunny'...
//answers old the strings 'yes', 'no'...
//this code assumes both lists have the same size, you can enforce this in a check or throw if not the case
Map<String, Map<String, Integer>> merged = new HashMap<>();
for (int j = 0; j < weathers.size(); j++) {
if (merged.containsKey(weathers.get(j))) {
Map<String, Integer> counts = merged.get(weathers.get(j));
counts.put(answers.get(j), counts.getOrDefault(answers.get(j), 0) + 1);
} else {
Map<String, Integer> newAnswer = new HashMap<>();
newAnswer.put(answer.get(j), 1);
merged.put(weathers.get(j), newAnswer);
}
}
return merged;
}
应用到上述代码的逻辑是循环遍历列表的每个事件,然后检查您的地图是否已经包含该天气。
- 如果是这种情况,您将获得已经存在的地图并增加该答案的数量(如果答案尚不存在,您将从零开始)
- 如果不是这种情况,您可以为该天气添加一张新地图,其中您只有第一个答案,计数为 1。
示例用法:
Map<String, Map<String, Integer>> resume = count(weathers, answers);
//How many times 'sunny' weather was 'maybe'?
Integer answer1 = resume.get("sunny").get("maybe");
//How many times 'rainy' weather was 'no'?
Integer answer2 = resume.get("rainy").get("no");
//etc.