How do I use Map.getOrDefault() default method in Java?

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 to fetch a value for a key, but aren’t sure if the key exists in the map. It helps you handle these scenarios without a need to write extra conditional code to check if the key is present (i.e., using containsKey(Object key)) before trying to get the value.

Here’s a common use case without getOrDefault():

Map<String, Integer> map = new HashMap<>();
// fill map...

Integer value;
if (map.containsKey("key")) {
    value = map.get("key");
} else {
    value = -1;
}

Here’s a basic example of how to use getOrDefault():

package org.kodejava.util;

import java.util.HashMap;
import java.util.Map;

public class MapGetOrDefaultExample {
    public static void main(String[] args) {
        Map<String, Integer> map = new HashMap<>();
        map.put("A", 1);
        map.put("B", 2);
        map.put("C", 3);

        // Get a value of the key "A". It will return value 1 as
        // "A" is present in the map.
        Integer value = map.getOrDefault("A", -1);
        System.out.println("Value: " + value);

        // Try to get a value of the key "Z". As "Z" is not present
        // in the map, it will return the default value -1.
        value = map.getOrDefault("Z", -1);
        System.out.println("Value: " + value);
    }
}

In this example, “Value: 1” and then “Value: -1” will be printed in the console. In the first case, the key “A” is in the map, so the associated value 1 is returned. In the second case, the key “Z” does not exist in the map, so the default value of -1 is returned.

How do I sort entries of a map by its keys or values?

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 main(String[] args) {
        Map<String, Integer> map = new HashMap<>();
        map.put("Apple", 10);
        map.put("Orange", 20);
        map.put("Banana", 30);

        Map<String, Integer> sortedByKey = map.entrySet().stream()
                .sorted(Map.Entry.comparingByKey())
                .collect(Collectors.toMap(
                        Map.Entry::getKey,
                        Map.Entry::getValue,
                        (oldValue, newValue) -> oldValue,
                        LinkedHashMap::new
                ));

        sortedByKey.forEach((key, value) -> System.out.println("Key: " + key + ", Value: " + value));
    }
}

Output:

Key: Apple, Value: 10
Key: Banana, Value: 30
Key: Orange, Value: 20

In the example map.entrySet().stream() creates a Stream consisting of the entries in the map. The sorted(Map.Entry.comparingByKey()) method sorts the entries based on keys. The sorted entries are collected back into a new LinkedHashMap (which maintains the order of its elements).

You can sort by values in a similar way:

package org.kodejava.util;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.stream.Collectors;

public class MapSortComparingByValue {
    public static void main(String[] args) {
        Map<String, Integer> map = new HashMap<>();
        map.put("Apple", 10);
        map.put("Orange", 20);
        map.put("Banana", 30);

        Map<String, Integer> sortedByValue = map.entrySet().stream()
                .sorted(Map.Entry.<String, Integer>comparingByValue().reversed())
                .collect(Collectors.toMap(
                        Map.Entry::getKey,
                        Map.Entry::getValue,
                        (oldValue, newValue) -> oldValue,
                        LinkedHashMap::new
                ));

        sortedByValue.forEach((key, value) -> System.out.println("Key: " + key + ", Value: " + value));
    }
}

Output:

Key: Banana, Value: 30
Key: Orange, Value: 20
Key: Apple, Value: 10

In this example, sorted(Map.Entry.<String, Integer>comparingByValue().reversed()) sorts the entries based on values in descending order. The reversed() method is used to reverse the natural ordering. If you want to sort in ascending order, omit the reversed() call.

How do I use the Map.forEach() default method?

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, Integer> map = new HashMap<>();
        map.put("Apple", 10);
        map.put("Orange", 20);
        map.put("Banana", 30);

        // Use the forEach method. Here, each key-value pair is printed.
        map.forEach((key, value) -> System.out.println("Key: " + key + ", Value: " + value));
    }
}

Output:

Key: Apple, Value: 10
Key: Orange, Value: 20
Key: Banana, Value: 30

In this example, a HashMap is created and populated with some data. The forEach method is then called on this map, with a lambda expression that accepts a key and a value, then prints them. The key and value parameters represent the current key-value pair the forEach method is handling. In this lambda expression, they are printed to the console.

This operation is applied to each entry in the map, hence the name forEach.

Using the forEach method with lambda expressions has several benefits:

  1. Improved Readability: Traditional iteration requires creating an iterator, a while or for loop, and handling each element. With forEach and lambdas, you can express what you want to do with each element clearly and concisely, making the code easier to read and understand
  2. Concurrency Safety: The forEach method is inherently safer to use in concurrent environments. You don’t need to worry about ConcurrentModificationException errors which you might get while using an Iterator and modifying the collection concurrently.
  3. Less Boilerplate Code: The forEach function in combination with a lambda function provides a way to iterate over a collection with fewer lines of code compared to using iterators
  4. Functional Programming: Lambda expressions and functional interfaces pave the way towards functional programming in Java, which allows for more expressive ways to manipulate collections.

Remember, although forEach can make your code more concise, it does not necessarily make it faster.

How do I use the List.sort() method?

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 of integers in ascending order:

package org.kodejava.util;

import java.util.ArrayList;
import java.util.List;

public class ListSortExample {
    public static void main(String[] args) {
        List<Integer> numbers = new ArrayList<>();
        numbers.add(3);
        numbers.add(1);
        numbers.add(4);
        numbers.add(1);
        numbers.add(5);

        // Use sort() to sort the numbers in ascending order
        numbers.sort(null);

        System.out.println(numbers); 
    }
}

Outputs:

[1, 1, 3, 4, 5]

You can also pass a Comparator to List.sort(). Here’s an example where we sort a list of strings by their length:

package org.kodejava.util;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

public class ListSortOtherExample {
    public static void main(String[] args) {
        List<String> words = new ArrayList<>();
        words.add("rat");
        words.add("elephant");
        words.add("cat");
        words.add("mouse");

        // Comparator for comparing string lengths
        Comparator<String> lengthComparator = (s1, s2) -> s1.length() - s2.length();

        // Use sort() to sort the words by their length
        words.sort(lengthComparator);

        System.out.println(words);
    }
}

Outputs:

[rat, cat, mouse, elephant]

In this case, the Comparator is a lambda expression that computes the difference in length between two strings. The List.sort() method uses this Comparator to determine the ordering of the strings in the list.

How do I use List.replaceAll() method?

The List.replaceAll() method was introduced in Java 8. This method replaces each element of the list with the result of applying the operator to that element. The operator or function you pass to replaceAll() should be a UnaryOperator.

Here is a simple example:

package org.kodejava.util;

import java.util.ArrayList;
import java.util.List;
import java.util.function.UnaryOperator;

public class ListReplaceAllExample {
    public static void main(String[] args) {
        List<Integer> numbers = new ArrayList<>();
        numbers.add(1);
        numbers.add(2);
        numbers.add(3);
        numbers.add(4);
        numbers.add(5);

        // Define an UnaryOperator to square each number
        UnaryOperator<Integer> square = n -> n * n;

        // Use replaceAll() method to square each number in the list
        numbers.replaceAll(square);

        System.out.println(numbers);
    }
}

Outputs:

[1, 4, 9, 16, 25]

In this example, the UnaryOperator square squares each element. The List.replaceAll() method applies this operator to all elements in the list.

Note that replaceAll() modifies the original list and does not return a new list. Please also be aware that this operation is in-place and hence modifies the original List. If you want to keep the original List unchanged, create a new List and add elements to it after applying the function.

The primary purpose of the List.replaceAll() method in Java is to perform an in-place transformation of all elements within a list based on a given unary function or operation.

A Unary function or operation is one that takes a single input and produces a result. In the context of replaceAll(), the unary operation is typically provided as a lambda expression or method reference which is applied to each element in the list in turn.

If successful, replaceAll() modifies the list such that each original element has been replaced by the result of applying the provided unary operation to that element. This operation is performed on the original list, and no new list is created, making it an efficient option for transforming large lists.

Here is an example which doubles each integer in a list:

package org.kodejava.util;

import java.util.ArrayList;
import java.util.List;

public class ListReplaceAllSecondExample {
    public static void main(String[] args) {
        List<Integer> ints = new ArrayList<>();

        ints.add(1);
        ints.add(2);
        ints.add(3);

        // Double every integer in the List
        ints.replaceAll(n -> n * 2);

        System.out.println(ints); 
    }
}

Outputs:

[2, 4, 6]

In conclusion, List.replaceAll() provides a convenient and efficient way to modify all elements in a list according to a specified operation or function. It’s especially useful when using the Streams API and functional programming techniques introduced in Java 8.