JAVA 8 / CATATAN</>↗Java 825 Jan 2024
Beginning from Java 8, the Map interface includes the remove(Object key, Object value) method, which removes the entry for the specified key only if it is currently mapped to the specified value. Here is a Java 8 way of accomplishing this: package org.kodejava.util; import java.util.HashMap; import java.util.Map; public class MapRemoveKeyValueExample { public static void main(String[] […]
JAVA 8 / CATATAN</>↗Java 825 Jan 2024
The compute(), computeIfAbsent(), and computeIfPresent() methods introduced in Java 8 provide powerful functionality to modify an existing map in a thread-safe manner. Here’s an example of how you might use each: compute(): Performs the given mapping function to the entry for the specified key. The function is applied even if key is not present or […]
JAVA 8 / CATATAN</>↗Java 825 Jan 2024
The Map.getOrDefault(Object key, V defaultValue) method in Java 8 is a convenience default method to return the value for a given key. If the map does not contain a mapping for the key, then it returns the default value. This method can be particularly useful in situations where you’re working with a map and need […]
JAVA 8 / CATATAN</>↗Java 825 Jan 2024
To sort the entries of a map by keys or values in Java, you can convert your Map to a Stream, sort it, and then collect it back into a Map. Here’s an example of sorting by keys: package org.kodejava.util; import java.util.HashMap; import java.util.Map; import java.util.LinkedHashMap; import java.util.stream.Collectors; public class MapSortComparingByKey { public static void […]
JAVA 8 / CATATAN</>↗Java 825 Jan 2024
The forEach() method in the Map interface in Java 8, allows you to iterate over each entry in the map, allowing you to use each key-value pair in some way. Here’s a basic usage of the forEach() method: package org.kodejava.util; import java.util.HashMap; import java.util.Map; public class MapForEachExample { public static void main(String[] args) { Map<String, […]
JAVA 8 / CATATAN</>↗Java 824 Jan 2024
The List.sort() method was introduced in Java 8. This method sorts the elements of the list on the basis of the given Comparator. If no comparator is provided, it will use the natural ordering of the elements (only if the elements are Comparable). Let’s take a look at an example where we sort a list […]