[英]Group JAVA Map keys based on tokens in string key
I have this requirement where I need to parse a text file and extract n-grams from it and store the n-gram mapping with their count in a map. 我有这个要求,我需要解析一个文本文件并从中提取n-gram,并将n-gram映射及其计数存储在地图中。 Now, the Map key is string which can have 1,2,3 words in it.
现在,Map键是字符串,其中可以包含1,2,3个单词。
eg ("mango", 10), ("facbook friend", 6), ("the rich guy", 3) 1<=n<=3
例如(“ mango”,10),(“ facbook friend”,6),(“ the rich guy”,3)1 <= n <= 3
Example mapping: 映射示例:
("mango", 2) (“芒果”,2)
("apple", 1) (“苹果”,1)
("mango tree", 5) (“芒果树”,5)
("facebook friend", 3) (“ facebook朋友”,3)
("facebook people", 8) (“ facebook人”,8)
("Bougth new watch", 2) (“ Bougth新款手表”,2)
Now, I want to sort the map based on keyword tokens length in map key. 现在,我想根据地图关键字中的关键字标记长度对地图进行排序。 like all 1 word key mapping should be first in map then 2 words then 3 words mapping.
像所有1个单词的键映射都应该首先在map中,然后是2个单词,然后是3个单词映射。
I tried using TreeMap but the main challenge was to define compareTo function for the sorting order.
我尝试使用TreeMap,但主要的挑战是为排序顺序定义compareTo函数。 Any ideas?
有任何想法吗? Like below method do not work.
像下面的方法不起作用。
Map<String, Integer> m = new TreeMap<>(Comparator.comparingInt(k -> k.split(" ").length));
m.put("mango tree", 5);
m.put("Bought new watch", 2);
m.put("apple", 1);
m.put("mango tree", 5);
m.put("Bought new watch", 2);
m.put("appl1", 1);
m.put("mango 1", 5);
m.put("Bought 1 watch", 2);
m.put("appl2", 1);
m.put("mango 2", 5);
m.put("Bought 2 watch", 2);
m.put("appl3", 1);
System.out.println(m);
Output: {apple=1, mango tree=5, Bought new watch=2} 输出:{apple = 1,芒果树= 5,购买了新手表= 2}
The following code inserts the records in order. 以下代码按顺序插入记录。
SortedMap<String, Integer> m = new TreeMap<>(new Comparator<String>() {
@Override
public int compare(String s1, String s2) {
int s2length = s2.split(" ").length;
int s1length = s1.split(" ").length;
return s2length>s1length?-1:s2length==s1length && s2.equals(s1)?0:1;
}
});
m.put("mango tree", 5);
m.put("you have to check this out too", 1);
m.put("apple", 1);
m.put("apple", 5);
m.put("you have to check this out", 1);
m.put("check this out", 1);
m.put("Bought new watch", 2);
m.put("check this out too", 1);
System.out.println(m);
You can do it using Collectors.toMap
with an ordered map supplier like so: 您可以使用
Collectors.toMap
和有序的地图提供者来完成此操作,如下所示:
Map<String, Integer> m = new HashMap<>();
m.put("mango tree", 5);
m.put("Bought new watch", 2);
m.put("apple", 1);
LinkedHashMap<String, Integer> sortedMap = m.entrySet().stream()
.sorted(Comparator.comparingInt(e -> e.getKey().split(" ").length))
.collect(Collectors.toMap(Map.Entry::getKey,
Map.Entry::getValue,
(o1, o2) -> o1,
LinkedHashMap::new));
System.out.println(sortedMap);
Output 产量
{apple=1, mango tree=5, Bought new watch=2}
You can also use the following .sorted(...
line: 您还可以使用以下
.sorted(...
行:
.sorted(Map.Entry.comparingByKey(Comparator.comparingInt(k -> k.split(" ").length)))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.