Java 如何跟踪两个相关LinkedList之间出现的次数?
我很难弄清楚如何跟踪两个相关LinkedList之间的事件 让我举例说明: 这些是有问题的链表 它们是相互依赖的,因为第一个列表中的每个值都对应于第二个列表中具有相同索引i的值。两个列表的长度始终相同Java 如何跟踪两个相关LinkedList之间出现的次数?,java,list,data-structures,linked-list,Java,List,Data Structures,Linked List,我很难弄清楚如何跟踪两个相关LinkedList之间的事件 让我举例说明: 这些是有问题的链表 它们是相互依赖的,因为第一个列表中的每个值都对应于第二个列表中具有相同索引i的值。两个列表的长度始终相同 {sunny, sunny, rainy, sunny, cloudy, sunny, ...} {yes, no, no, maybe, yes, no, ...} 我需要的是以某种方式跟踪事件的“成对”。 例如: sunny -> 1 yes, 1 maybe, 2 no rainy
{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个选项。可能有更多或更少。此外,列表中项目的名称以前不知道
所以是的,我想知道在我走到死胡同的时候,存储这些信息的最佳方式是什么
非常感谢您的帮助。您可以使用
地图进行操作。感谢您的快速响应。代码对我来说是有意义的,但由于某种原因,我得到了一个不支持的操作异常,或者更准确地说是一个ImmutableCollection异常。我从Map.Entry循环调用该函数,其中List是“weather”列表,因此我将Entry.getValue()参数传递给您编写的函数。我假设我在某个地方犯了一个错误,但我无法指出它。哦,是的,这是因为Map.of()创建了一个不可变的映射,但在下一次迭代中,您尝试再次更新它。这在这里没有什么用处。我会更新我的密码谢谢!现在它工作得很好。你帮我节省了很多时间!
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;
}
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.