Last active
July 3, 2016 22:17
-
-
Save tonvanbart/4a13d1657f4ac5e9b40ebb5aefa7770a to your computer and use it in GitHub Desktop.
Combine two maps a and b so that for a key in a, the value is b(a(key))
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package org.vanbart; | |
import org.junit.Before; | |
import org.junit.Test; | |
import java.util.HashMap; | |
import java.util.Map; | |
import static org.hamcrest.core.Is.is; | |
import static org.junit.Assert.assertNull; | |
import static org.junit.Assert.assertThat; | |
public class ReplaceAll { | |
private Map<String, String> mapA = new HashMap<>(); | |
private Map<String, String> mapB = new HashMap<>(); | |
private Map<String, String> combined = new HashMap<>(); | |
@Before | |
public void setup() { | |
mapA.put("1", "a"); | |
mapA.put("2", "b"); | |
mapA.put("4", "d"); | |
mapB.put("a", "one"); | |
mapB.put("b", "two"); | |
mapB.put("c", "three"); | |
} | |
@Test | |
public void testReplaceAll() { | |
mapA.replaceAll((k, v) -> mapB.get(v)); | |
assertThat(mapA.get("1"), is("one")); | |
assertThat(mapA.get("2"), is("two")); | |
assertNull(mapA.get("4")); | |
} | |
@Test | |
public void testCompute() { | |
for (Map.Entry<String, String> entry: mapA.entrySet()) { | |
combined.compute(entry.getKey(), (k,v) -> mapB.get(entry.getValue())); | |
} | |
assertThat(combined.get("1"), is("one")); | |
assertThat(combined.get("2"), is("two")); | |
assertNull(combined.get("4")); | |
} | |
@Test | |
public void testCompute2() { | |
for (Map.Entry<String, String> entry: mapA.entrySet()) { | |
combined.compute(entry.getKey(), (k,v) -> remap(k)); | |
} | |
assertThat(combined.get("1"), is("one")); | |
assertThat(combined.get("2"), is("two")); | |
assertNull(combined.get("4")); | |
} | |
private String remap(String key) { | |
return mapB.get(mapA.get(key)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment