import java.util.Iterator;import java.util.Map;
public class MapUtils {static interface ItemCallback<K, V> {void handler(K key, V value, Map<K, V> map);}
public static <K, V> void forEach(Map<K, V> map, ItemCallback<K, V> callback) {Iterator<Map.Entry<K, V>> it = map.entrySet().iterator();
while (it.hasNext()) {Map.Entry<K, V> entry = it.next();
callback.handler(entry.getKey(), entry.getValue(), map);}}
public static <K, V> void printMap(Map<K, V> map) {forEach(map, new ItemCallback<K, V>() {@Overridepublic void handler(K key, V value, Map<K, V> map) {System.out.println(key + " = " + value);}});}}
示例
下面是它的使用示例。请注意,Map的类型是由方法推断的。
import java.util.*;
public class MapPrinter {public static void main(String[] args) {List<Map<?, ?>> maps = new ArrayList<Map<?, ?>>() {private static final long serialVersionUID = 1L;{add(new LinkedHashMap<String, Integer>() {private static final long serialVersionUID = 1L;{put("One", 0);put("Two", 1);put("Three", 3);}});
add(new LinkedHashMap<String, Object>() {private static final long serialVersionUID = 1L;{put("Object", new Object());put("Integer", new Integer(0));put("Double", new Double(0.0));}});}};
for (Map<?, ?> map : maps) {MapUtils.printMap(map);System.out.println();}}}
/* For example, this could be a map object */Map<String, Integer> MAP = new Map<>();
// Do something like put keys/value pairs into the map, etc...MAP.put("Denver", 35);MAP.put("Patriots", 14);
/* Then, simply use a for each loop like this to iterate */for (Object o : MAP.entrySet()) {Map.Entry pair = (Map.Entry) o;// Do whatever with the pair here (i.e. pair.getKey(), or pair.getValue();}
HashMap<Integer,Integer> hm = new HashMap<Integer, Integer>();/** Logic to put the Key,Value pair in your HashMap hm*/
// Print the key value pair in one line.
hm.forEach((k, v) -> System.out.println("key: " + k + " value:" + v));
// Just copy and paste above line to your code.
int counter = 0;HashMap<String, String> m = new HashMap<String, String>();for(int i = 0;i<items.length;i++){m.put("firstname"+i, items.get(i).getFirstName());counter = i;}
m.put("recordCount",String.valueOf(counter));
如果你想恢复:
int recordCount = Integer.parseInf(m.get("recordCount"));for(int i =0 ;i<recordCount;i++){System.out.println("First Name :" + m.get("firstname"+i));}
Map<String,String> sampleMap = new HashMap<>();for (sampleMap.Entry<String,String> entry : sampleMap.entrySet()) {String key = entry.getKey();String value = entry.getValue();
/* your Code as per the Business Justification */
}
使用Java8
Map<String,String> sampleMap = new HashMap<>();
sampleMap.forEach((k, v) -> System.out.println("Key is : " + k + " Value is : " + v));