简体   繁体   中英

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). 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.

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可用于装饰另一张地图,使其具有多个键值。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM