For Java 7 there is nothing more that you can do, you are already doing it in the best way.
I am adding this answer as a reference to show that for such a case, using Lambda Expressions in Java 8 would be even worse. See this example:
public static void main(String[] args) { Map<String, String> map1 = new HashMap<>(); final Map<String, String> map2 = new HashMap<>(); for ( int i=0; i<100000; i++ ){ map1.put("k"+i, "v"+i); map2.put("v"+i, "val"+i); } long time; long prev_time = System.currentTimeMillis(); for (Map.Entry<String, String> entry : map1.entrySet()) { map1.put(entry.getKey(), map2.get(entry.getValue())); } time = System.currentTimeMillis() - prev_time; System.out.println("Time after for loop " + time); map1 = new HashMap<>(); for ( int i=0; i<100000; i++ ){ map1.put("k"+i, "v"+i); } prev_time = System.currentTimeMillis(); map1.replaceAll((k, v) -> map2.get(v)); time = System.currentTimeMillis() - prev_time; System.out.println("Time after for loop " + time); }
The output for this would be:
Time after for loop 40 Time after for loop 100
The second cycle is variable, but always larger than the first.
I am not a Lambda specialist, but I think that it needs more processing with it than a simple "foreach" of the first script
Running this test again and again you get for lambda almost always twice as much time for the first case of "foreach".
source share