Java 8 introduced the new default methods to Map interface which stores lazied-computed value and doesn't break map contract. We can be based on below to write clean code.
getOrDefault
Returns the value to which the specified key is mapped, or defaultValue if this map contains no mapping for the key.
public void testGetOfDefault()
{
Map<String, Integer> studentGrades = new HashMap<>();
Assert.assertThat(studentGrades.getOrDefault("Chris", 0), equalTo(new Integer(0)));
}
forEach
Performs the give action for each entry in this map util all entries have been processed or the action throws an exception.
public void testForEach()
{
Map<String, Integer> collector = new HashMap()
{ { put("A", 99); put("B", 80); put("C", 70); } };
collector.forEach((key, value) -> System.out.println(String.format("%s => %s", key, value)));
}
replaceAll
Replaces each entry's value with the result of invoking the given function on that entry util all entries have been processed or the function throws an exception.
public void testReplaceAll()
{
Map<String, Integer> collector = new HashMap()
{ { put("A", 99); put("B", 82); put("C", 71); } };
collector.replaceAll((key, value) -> value < 90 ? value + 10 : value);
assertThat(collector, hasEntry("A", 99));
assertThat(collector, hasEntry("B", 92));
assertThat(collector, hasEntry("C", 81));
}
putIfAbsent
If the specified key is not already associated with a value is mapped to null associates if with the given value and return null, else returns the current value.
public void testPutIfAbsent()
{
Map<String, Integer> counters = new HashMap()
{{ put("c0", 0); }};
counters.putIfAbsent("c0", 99);
counters.putIfAbsent("c1", 99);
assertEquals(Integer.valueOf(0), counters.get("c0"));
assertEquals(Integer.valueOf(99), counters.get("c1"));
}
computeIfAbsent
If the specified key is not already associated with a value, attempts too compute its value using the given function and enters it into this map unless null.
public void testComputeIfAbsent()
{
Map<String, List<Integer>> counters = new HashMap<>();
counters.computeIfAbsent("key", k -> new ArrayList<>()).addAll(Arrays.asList(1, 3, 5));
Assert.assertThat(counters.get("key"), hasItems(1, 3, 5));
}
computeIfPresent
If the value for the specified key is present and not-null, attempts to compute a new mapping given the key and its current mapped value.
public void testComputeIfPresent()
{
Map<String, Integer> map = new HashMap()
{{
put("key", 2);
}};
map.computeIfPresent("key", (k, v) -> v / 2);
assertThat(map.get("key"), equalTo(1));
}
merge
If the value for the specified key is present and non-null, attempts to compute a new mapping give the key and its current mapped value.
public void testMergeValue()
{
Map<String, String> holder = new HashMap();
holder.put("chris", "^^~");
holder.merge("chris", "Java", (v1, v2) -> v1.concat(v2));
Assert.assertThat(holder.get("chris"), is("^^~Java"));
}
No comments:
Post a Comment