Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Convert Map to List in Java 8

DZone's Guide to

Convert Map to List in Java 8

A brief code snippet to demonstrate how to convert a map to a list in Java from our newest MVB, Yong Mook Kim!

· Java Zone ·
Free Resource

Get the Edge with a Professional Java IDE. 30-day free trial.

A Java 8 example to convert a Map to a List

ConvertMapToList.java

package com.mkyong.example;

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

public class ConvertMapToList {

    public static void main(String[] args) {

        Map<Integer, String> map = new HashMap<>();
        map.put(10, "apple");
        map.put(20, "orange");
        map.put(30, "banana");
        map.put(40, "watermelon");
        map.put(50, "dragonfruit");

        System.out.println("\n1. Export Map Key to List...");

        List<Integer> result = map.entrySet().stream()
                .map(x -> x.getKey())
                .collect(Collectors.toList());

        result.forEach(System.out::println);

        System.out.println("\n2. Export Map Value to List...");

        List<String> result2 = map.entrySet().stream()
                .map(x -> x.getValue())
                .collect(Collectors.toList());

        result2.forEach(System.out::println);


    }

}

Output

1. Export Map Key to List...
50
20
40
10
30

2. Export Map Value to List...
dragonfruit
orange
watermelon
apple
banana

References

  1. Java 8 – Convert List to Map
  2. Java 8 forEach examples

Get the Java IDE that understands code & makes developing enjoyable. Level up your code with IntelliJ IDEA. Download the free trial.

Topics:
java 8 ,java ,map ,list

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}