Java反转地图

时间:2016-12-06 23:29:53

标签: java arraylist hashmap invert

我需要反转原始地图。哪个类型为<Integer, String>,如{1 = A, 2 = A, 3 = B....}。我想创建一个StringArrayList的新地图,因为如果1 = A2 = A,我希望有这样的内容:A = [1, 2]

那我怎么能这样做呢?

2 个答案:

答案 0 :(得分:5)

您可以使用Java 8 stream API轻松完成此操作,下面是一个示例:

public static void main(String[] args) throws FileNotFoundException {

    Map<Integer, String> map = new HashMap<>();
    map.put(1, "A");
    map.put(2, "A");
    map.put(3, "B");

    Map<String, List<Integer>> invertedMap = map.entrySet()
    .stream()
    .collect(Collectors.groupingBy(Entry::getValue, 
            Collectors.mapping(Entry::getKey, Collectors.toList())));

    System.out.println(invertedMap);

}

答案 1 :(得分:4)

你可以试试这个:

HashMap<Integer, String> original = new HashMap<>();
HashMap<String, ArrayList<Integer>> inverted = new HashMap<>();

original.put(1, "A");
original.put(2, "B");
original.put(3, "C");
original.put(4, "A");

for (Integer key: original.keySet()) {
    String newKey = original.get(key);

    inverted.computeIfAbsent(newKey, k -> new ArrayList<>());
    inverted.get(newKey).add(key);

}
System.out.println(original);
System.out.println(inverted);

所以,让我们说HashMap<Integer, String> original{1=A, 2=B, 3=C, 4=A},然后你会得到{A=[1, 4], B=[2], C=[3]}

编辑:如果您想要一个更通用的版本,如@ Mr.Polywhirl建议的那样,您可以使用:

public static final <T, U> Map<U, List<T>> invertMap(Map<T, U> map) {
    HashMap<U, List<T>> invertedMap = new HashMap<>();

    for (T key : map.keySet()) {
        U newKey = map.get(key);

        invertedMap.computeIfAbsent(newKey, k -> new ArrayList<>());
        invertedMap.get(newKey).add(key);

    }

    return invertedMap;
}