是否有可能实现一个HashMap有一个键和两个值。就像HashMap?

请帮助我,也通过告诉(如果没有办法)任何其他方法来实现三个值的存储与一个作为关键?


当前回答

使用Java收集器

// Group employees by department
Map<Department, List<Employee>> byDept = employees.stream()
                    .collect(Collectors.groupingBy(Employee::getDepartment));

你的钥匙在哪个部门

其他回答

另一个不错的选择是使用Apache Commons中的MultiValuedMap。查看页面顶部的所有已知实现类,了解专门的实现。

例子:

HashMap<K, ArrayList<String>> map = new HashMap<K, ArrayList<String>>()

可以用

MultiValuedMap<K, String> map = new MultiValuedHashMap<K, String>();

So,

map.put(key, "A");
map.put(key, "B");
map.put(key, "C");

Collection<String> coll = map.get(key);

将导致集合coll中包含“A”、“B”和“C”。

我使用Map<KeyType, Object[]>将多个值与Map中的一个键关联起来。这样,我就可以存储与一个键关联的多个不同类型的值。你必须注意保持正确的插入和从Object[]中检索的顺序。

例子: 考虑一下,我们想要存储Student信息。键是id,而我们想要存储姓名,地址和电子邮件与学生相关联。

       //To make entry into Map
        Map<Integer, String[]> studenMap = new HashMap<Integer, String[]>();
        String[] studentInformationArray = new String[]{"name", "address", "email"};
        int studenId = 1;
        studenMap.put(studenId, studentInformationArray);

        //To retrieve values from Map
        String name = studenMap.get(studenId)[1];
        String address = studenMap.get(studenId)[2];
        String email = studenMap.get(studenId)[3];

最简单的方法是使用谷歌集合库:

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<String, String> 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链接:https://mvnrepository.com/artifact/com.google.collections/google-collections/1.0-rc2

更多相关信息:http://tomjefferys.blogspot.be/2011/09/multimaps-google-guava.html

使用Java收集器

// Group employees by department
Map<Department, List<Employee>> byDept = employees.stream()
                    .collect(Collectors.groupingBy(Employee::getDepartment));

你的钥匙在哪个部门

如果你使用Spring Framework。有:org.springframework.util.MultiValueMap。

创建不可修改的多值映射:

Map<String,List<String>> map = ...
MultiValueMap<String, String> multiValueMap = CollectionUtils.toMultiValueMap(map);

或者使用org.springframework.util.LinkedMultiValueMap