首页 > 解决方案 > 如何跟踪两个依赖 LinkedLists 之间的出现次数?

问题描述

我在弄清楚如何跟踪两个相关的 LinkedList 之间的事件时遇到了一些麻烦。

让我用一个例子来详细说明:

这些是有问题的链表。

它们是相关的,因为第一个列表中的每个值都对应于具有相同索引 i 的第二个列表中的值。两个列表的长度始终相同。

{sunny, sunny, rainy, sunny, cloudy, sunny, ...}
{yes, no, no, maybe, yes, no, ...}

我需要以某种方式跟踪事件的“对”。例如:

sunny -> 1 yes, 1 maybe, 2 no
rainy -> 1 no
cloudy -> 1 yes

注意:不一定有 3 个选项。可以有更多或更少。此外,列表项目的名称以前也不知道。

所以是的,我想知道哪种方法是存储这些信息的最佳方式,因为我已经走到了死胡同。

任何帮助表示赞赏。

标签: javalistdata-structureslinked-list

解决方案


您可以使用Map<String, Map<String, Integer>.

  • 外层地图的关键是天气(sunnyrainy
  • 该值是另一个映射,其中包含每个可能的值 ( 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.

推荐阅读