Here you can find the source of reverseMap(List listSeq)
Parameter | Description |
---|---|
listSeq | to reverse |
public static HashMap reverseMap(List listSeq)
//package com.java2s; /*/*from w w w . java 2s. c o m*/ * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class Main { /** * "{:a 1 :b 1 :c 2} -> {1 [:a :b] 2 :c}" * * Example usage in java: * Map<Integer, String> tasks; * Map<String, List<Integer>> componentTasks = Utils.reverse_map(tasks); * * The order of he resulting list values depends on the ordering properties * of the Map passed in. The caller is responsible for passing an ordered * map if they expect the result to be consistently ordered as well. * * @param map to reverse * @return a reversed map */ public static <K, V> HashMap<V, List<K>> reverseMap(Map<K, V> map) { HashMap<V, List<K>> rtn = new HashMap<V, List<K>>(); if (map == null) { return rtn; } for (Map.Entry<K, V> entry : map.entrySet()) { K key = entry.getKey(); V val = entry.getValue(); List<K> list = rtn.get(val); if (list == null) { list = new ArrayList<K>(); rtn.put(entry.getValue(), list); } list.add(key); } return rtn; } /** * "[[:a 1] [:b 1] [:c 2]} -> {1 [:a :b] 2 :c}" * Reverses an assoc-list style Map like reverseMap(Map...) * * @param listSeq to reverse * @return a reversed map */ public static HashMap reverseMap(List listSeq) { HashMap<Object, List<Object>> rtn = new HashMap(); if (listSeq == null) { return rtn; } for (Object entry : listSeq) { List listEntry = (List) entry; Object key = listEntry.get(0); Object val = listEntry.get(1); List list = rtn.get(val); if (list == null) { list = new ArrayList<Object>(); rtn.put(val, list); } list.add(key); } return rtn; } public static <S, T> T get(Map<S, T> m, S key, T def) { T ret = m.get(key); if (ret == null) { ret = def; } return ret; } }