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

Build vs Buy a Data Quality Solution: Which is Best for You? Gain insights on a hybrid approach. Download white paper now!

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

Build vs Buy a Data Quality Solution: Which is Best for You? Maintaining high quality data is essential for operational efficiency, meaningful analytics and good long-term customer relationships. But, when dealing with multiple sources of data, data quality becomes complex, so you need to know when you should build a custom data quality tools effort over canned solutions. Download our whitepaper for more insights into a hybrid approach.

Topics:
java 8 ,java ,map ,list

Published at DZone with permission of Yong Mook Kim, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}