简体   繁体   English

如何在Java中按(SQL)执行分组

[英]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.

相关问题 如何在 Java 中执行 SQL 插入 - How to perform an SQL insert in Java 如何使用Java应用程序在SQL数据库中执行搜索? - How to perform a search in an SQL database with a java application? Java 使用 2 列表执行过滤和分组和执行媒体 - Java perform filter and group and perform media with 2 list 如何编写Java正则表达式,对不在注释中的组执行.replaceFirst? - How can I write a regex in Java that will perform a .replaceFirst on a group that is not in a comment? java-如何执行SQL注入以进行测试? - java-How to perform SQL injection for testing purposes? 如何在过程中使用regexp作为参数通过Java执行sql过程? - How to perform sql procedure by java using regexp as parameter in procedure? 如何对java.sql.Time对象执行算术运算? - How to perform arithmetic on java.sql.Time objects? 如何循环Java中的stream组对每个组中的Strings进行操作 - How to loop through stream groups in Java to perform operations on Strings in each group Java:如何使用Java jdbc for SQL Server使用标识列执行批量插入 - Java: how to perform batch insert with identity column using java jdbc for Sql Server 如何使用Java有效地对SQL查询输出进行分组? - How to efficiently group SQL query output using Java?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM