如果我有一个用Java实现Map接口的对象,并且我希望对其中包含的每一对进行迭代,那么最有效的方法是什么?
元素的顺序是否取决于我对接口的特定映射实现?
如果我有一个用Java实现Map接口的对象,并且我希望对其中包含的每一对进行迭代,那么最有效的方法是什么?
元素的顺序是否取决于我对接口的特定映射实现?
当前回答
如果您通过Map进行迭代的原因是对值执行操作并写入结果Map。我建议在GoogleGuavaMaps类中使用转换方法。
import com.google.common.collect.Maps;
将地图添加到导入后,可以在地图上使用Maps.transformValues和Maps.transform Entries,如下所示:
public void transformMap(){
Map<String, Integer> map = new HashMap<>();
map.put("a", 2);
map.put("b", 4);
Map<String, Integer> result = Maps.transformValues(map, num -> num * 2);
result.forEach((key, val) -> print(key, Integer.toString(val)));
// key=a,value=4
// key=b,value=8
Map<String, String> result2 = Maps.transformEntries(map, (key, value) -> value + "[" + key + "]");
result2.forEach(this::print);
// key=a,value=2[a]
// key=b,value=4[b]
}
private void print(String key, String val){
System.out.println("key=" + key + ",value=" + val);
}
其他回答
Java 8
我们得到了接受lambda表达式的forEach方法。我们也有流API。考虑一张地图:
Map<String,String> sample = new HashMap<>();
sample.put("A","Apple");
sample.put("B", "Ball");
在关键点上重复:
sample.keySet().forEach((k) -> System.out.println(k));
遍历值:
sample.values().forEach((v) -> System.out.println(v));
遍历条目(使用forEach和Streams):
sample.forEach((k,v) -> System.out.println(k + ":" + v));
sample.entrySet().stream().forEach((entry) -> {
Object currentKey = entry.getKey();
Object currentValue = entry.getValue();
System.out.println(currentKey + ":" + currentValue);
});
流的优点是,如果我们需要,它们可以很容易地并行化。我们只需要使用parallelStream()代替上面的stream()。
forEachOrdered与forEach的流?forEach不遵循遭遇顺序(如果已定义),本质上是非确定性的,正如forEachOrdered一样。因此forEach不保证订单会被保留。还要查看此项了解更多信息。
如果您通过Map进行迭代的原因是对值执行操作并写入结果Map。我建议在GoogleGuavaMaps类中使用转换方法。
import com.google.common.collect.Maps;
将地图添加到导入后,可以在地图上使用Maps.transformValues和Maps.transform Entries,如下所示:
public void transformMap(){
Map<String, Integer> map = new HashMap<>();
map.put("a", 2);
map.put("b", 4);
Map<String, Integer> result = Maps.transformValues(map, num -> num * 2);
result.forEach((key, val) -> print(key, Integer.toString(val)));
// key=a,value=4
// key=b,value=8
Map<String, String> result2 = Maps.transformEntries(map, (key, value) -> value + "[" + key + "]");
result2.forEach(this::print);
// key=a,value=2[a]
// key=b,value=4[b]
}
private void print(String key, String val){
System.out.println("key=" + key + ",value=" + val);
}
每个地图
简单地使用Map::forEach,其中键和值都传递给BiConsumer怎么样?
map.forEach((k,v)->{
System.out.println(k+"->"+v);
});
package com.test;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
public class Test {
public static void main(String[] args) {
Map<String, String> map = new HashMap<String, String>();
map.put("ram", "ayodhya");
map.put("krishan", "mathura");
map.put("shiv", "kailash");
System.out.println("********* Keys *********");
Set<String> keys = map.keySet();
for (String key : keys) {
System.out.println(key);
}
System.out.println("********* Values *********");
Collection<String> values = map.values();
for (String value : values) {
System.out.println(value);
}
System.out.println("***** Keys and Values (Using for each loop) *****");
for (Map.Entry<String, String> entry : map.entrySet()) {
System.out.println("Key: " + entry.getKey() + "\t Value: "
+ entry.getValue());
}
System.out.println("***** Keys and Values (Using while loop) *****");
Iterator<Entry<String, String>> entries = map.entrySet().iterator();
while (entries.hasNext()) {
Map.Entry<String, String> entry = (Map.Entry<String, String>) entries
.next();
System.out.println("Key: " + entry.getKey() + "\t Value: "
+ entry.getValue());
}
System.out
.println("** Keys and Values (Using java 8 using lambdas )***");
map.forEach((k, v) -> System.out
.println("Key: " + k + "\t value: " + v));
}
}
在Java 1.4中尝试:
for( Iterator entries = myMap.entrySet().iterator(); entries.hasNext();){
Entry entry = (Entry) entries.next();
System.out.println(entry.getKey() + "/" + entry.getValue());
//...
}