这个问题是this thread的延续:
简而言之:为了解决我的问题,我想使用Map<Set<String>, String>
.
但是,当我在 Excel 中对数据条目进行排序后,删除不必要的参数,结果如下:
flow content ==> content content
flow content ==> content depth distance
flow content ==> content depth within
flow content ==> content depth within distance
flow content ==> content within
flow content ==> content within distance
如果是这种情况,我的 HashMap 有多个唯一键。我该如何解决这个问题...有人有任何想法吗?
我在想也许Map<Set <String>, List <String>>
这样我就可以做类似的事情:
Set <flow content>, List <'content content','content depth distance','content depth within ', ..., 'content within distance'>
但是因为我正在逐行解析条目我无法弄清楚如何将相同重复键(流内容)的值存储到同一列表中并将其添加到 map 。
有人对如何在 Java 中完成此操作有一个粗略的逻辑吗?
提前致谢。
--编辑:
尝试 Multimap 但不知何故遇到了一些小问题:
public static void main(String[] args) {
File file = new File("apriori.txt");
Multimap<Set <String>, String> mm = HashMultimap.create();
Set<String> s = null;
List l = null;
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(file));
String line = "";
while ((line = br.readLine()) != null) {
//Regex delete only tokenize
String[] string = line.split(";");
System.out.println(string[0] + " " + string[1]);
StringTokenizer st = new StringTokenizer(string[0].trim());
while (st.hasMoreTokens()) {
//System.out.println(st.nextToken());
s = new HashSet<String>();
s.add(st.nextToken());
}
mm.put(s,string[1]);
}
// dispose all the resources after using them.
br.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Set<String> t = new HashSet<String>();
t.add("content");
t.add("by");
String str = mm.get(t).toString();
System.out.println(str);
for (Map.Entry<Set <String>, String> e : mm.entries()) {
System.out.println(e);
}
}
apriori.txt
byte_jump ; msg
byte_jump ; msg by
content ; msg
content by ; flow
content by ; msg
content by ; msg flow
content by byte_jump ; msg
content byte_jump ; by
content byte_jump ; msg
content byte_jump ; msg by
显然 forloop 的输出:
[content]= msg
[by]= flow
[by]= msg
[by]= msg flow
[byte_jump]= msg
[byte_jump]= by
[byte_jump]= msg by
而不是[content by]=消息流
为什么会这样呢?我尝试过并且有效。但我需要 Set 来比较字符串,无论位置如何。我能做什么?
最佳答案
逻辑本质上是:
- 按照您的建议映射到列表
- 要将某些内容放入 map 中,请检索与该键对应的列表
- 如果列表为空,则创建一个新列表并将键映射到该新列表
- 将项目添加到列表
正如另一位发帖者所提到的,您可以考虑使用标准的多 map 库类,例如 Google Collections 中提供的类。 (我个人会自己实现它,因为它非常简单,并且在我看来并不真正需要一个完整的额外库,但里程有所不同。)
关于java - HashMap 多唯一键问题(Java),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2704882/