[英]How to perform a group by (sql) in Java
I have a text file which looks like this: 我有一个看起来像这样的文本文件:
code appearance
----------------
j4t8 1
fj89 3
pf6n 1
j4t8 5
And I want to sort by the codes which appear the most. 我想按显示最多的代码进行排序。 As you can see (and since I want to perform a group by) there are duplicate codes, so using HashMap would be a problem (duplicate keys). 如您所见(并且由于我要执行分组依据),所以有重复的代码,因此使用HashMap将是一个问题(重复的键)。 Any ideas? 有任何想法吗?
You can use 您可以使用
HashMap map = new HashMap<String, List<Integer>>();
The appearances will be stored in a list associated with every code. 外观将存储在与每个代码关联的列表中。 Then given a code you just retrieve the list of integers and iterate over it. 然后给定代码,您只需检索整数列表并对其进行迭代。
You need a Collection of Pair objects. 您需要成对对象的集合。 Each pair holds the code and the appearance. 每对都有代码和外观。 You then sort the collection using a Comparator, which only compares the appearance in each Pair object, and disregards the code. 然后,您可以使用比较器对集合进行排序,该比较器仅比较每个Pair对象中的外观,而忽略代码。
don't know if this is the best solution but you could create a map of a list like this: 不知道这是否是最好的解决方案,但是您可以创建一个列表列表,如下所示:
Map<String, List<Integer>> map = new HahsMap<String, List<Integer>>();
if(map.contains.(key))
{
map.get(key).add(new_appearance_value);
}
else
{
List<Integer> app = new ArrayList<Integer>();
app.add(new_appearance_value);
map.put(key, app);
}
Where the map key would be the code and the values of appearance would go into the list. 映射键将是代码,外观值将进入列表。
Note: to determine which code has more appearances just check for the size of the list of each code. 注意:要确定哪个代码显示更多,只需检查每个代码列表的大小即可。
Commons Collections MultiValueMap可用于装饰另一张地图,使其具有多个键值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.