HashMap with multiple values under the same key

前端 未结 22 1847
旧时难觅i
旧时难觅i 2020-11-22 06:49

Is it possible for us to implement a HashMap with one key and two values. Just as HashMap?

Please do help me, also by telling (if there is no way) any other way to

22条回答
  •  情歌与酒
    2020-11-22 07:00

    The easiest way would be to use a google collection library:

    import com.google.common.collect.ArrayListMultimap;
    import com.google.common.collect.Multimap;
    
    public class Test {
    
        public static void main(final String[] args) {
    
            // multimap can handle one key with a list of values
            final Multimap cars = ArrayListMultimap.create();
            cars.put("Nissan", "Qashqai");
            cars.put("Nissan", "Juke");
            cars.put("Bmw", "M3");
            cars.put("Bmw", "330E");
            cars.put("Bmw", "X6");
            cars.put("Bmw", "X5");
    
            cars.get("Bmw").forEach(System.out::println);
    
            // It will print the:
            // M3
            // 330E
            // X6
            // X5
        }
    
    }
    

    maven link: https://mvnrepository.com/artifact/com.google.collections/google-collections/1.0-rc2

    more on this: http://tomjefferys.blogspot.be/2011/09/multimaps-google-guava.html

提交回复
热议问题