Add Map Values To List In Java 8

3 min read Jun 22, 2024
Add Map Values To List In Java 8

Add Map Values to List in Java 8

This article will guide you on how to efficiently add map values to a list using Java 8's powerful features.

Using stream() and collect()

The most common approach is leveraging the stream() and collect() methods of Java 8's stream API. This method allows you to iterate through the map's entries and extract the values, then collect them into a new list.

import java.util.*;
import java.util.stream.Collectors;

public class MapToList {

    public static void main(String[] args) {

        Map myMap = new HashMap<>();
        myMap.put("Apple", 1);
        myMap.put("Banana", 2);
        myMap.put("Orange", 3);

        List valuesList = myMap.entrySet().stream()
                .map(Map.Entry::getValue)
                .collect(Collectors.toList());

        System.out.println("List of values: " + valuesList);
    }
}

Explanation:

  1. myMap.entrySet().stream(): This line creates a stream from the map's entry set.
  2. map(Map.Entry::getValue): We apply the map operation to extract the value from each entry using a method reference.
  3. collect(Collectors.toList()): This operation collects the mapped values into a new list.

Using forEach()

You can also achieve the same result using a traditional loop with forEach():

import java.util.*;

public class MapToList {

    public static void main(String[] args) {

        Map myMap = new HashMap<>();
        myMap.put("Apple", 1);
        myMap.put("Banana", 2);
        myMap.put("Orange", 3);

        List valuesList = new ArrayList<>();
        myMap.forEach((key, value) -> valuesList.add(value));

        System.out.println("List of values: " + valuesList);
    }
}

Explanation:

  1. myMap.forEach((key, value) -> valuesList.add(value));: This line iterates through the map using forEach(), adding the value of each entry to the valuesList.

Choosing the right approach

  • Stream API: The stream approach is considered more concise and readable, especially for complex operations.
  • forEach() loop: The forEach() loop is more suitable for simple scenarios where you need direct control over the list modification.

Remember:

  • Both methods effectively achieve the goal of adding map values to a list.
  • Choose the method that aligns best with your coding style and the complexity of your task.

Related Post


Latest Posts