Need help matching this data in Java

I'm having trouble displaying this data

1 35 1 30 1 20 2 10 3 40 3 25 3 15 

I tried using HashMap, but it will only be displayed for the last occurrence of this data.

+4
source share
5 answers

The Map and HashMap behavior that you describe is the intended behavior, as other commentators have noted. What you want is a multimap. You can collapse your own (don't do this - other commentators offer maps for lists, but this quickly becomes cumbersome). If you really want to collapse your own, collapse your own common multimap with list / preset values ​​and hide the complexity. ) or use Guava multimap . Example:

 import com.google.common.collect.HashMultimap; import com.google.common.collect.SetMultimap; public static void main(String[] args) { final SetMultimap<Integer, Integer> foo = HashMultimap.create(); foo.put( 1,35); foo.put( 1,30); foo.put( 1,20); foo.put( 2,10); foo.put( 3,40); foo.put( 3,25); foo.put( 3,15); System.out.println(foo); } 

Output:

{1 = [35, 20, 30], 2 = [10], 3 = [25, 40, 15]}

If you want to access values, there are several ways, depending on what you want to do. Just calling get(Integer key) will return a collection of values.

Also, check out this answer , which references a lot of good in Guava.

+8
source

The documentation states :

open interface Map
An object that maps keys to values. the card cannot contain duplicate keys; each key can display no more than one value.

Instead, you can associate a list of numbers with each key.

+6
source

You can use Map<Long, List<Long>> (or any other type) to solve this problem.

+4
source

A Map has only one value for a key. You can use the Multimap interface from Guava / Google Collections to store multiple values ​​for a key.

+2
source

Or create a pair <F, S> and put them in a list

List <Pair <Integer, Integer β†’

0
source

Source: https://habr.com/ru/post/1332285/


All Articles