Convert a Stream to LinkedHashMap in Java 8

116 total views, 1 views today

Welcome to Java 8 series. In this tutorial, you will learn about how to convert a Stream to a LinkedHashMap in Java 8.

If you would like to learn more about Java Stream operations.Please check out this link.

In order, to convert a stream to a collection we have to use Collectors api provided in Java 8. So we have to import the bellow package.

java.util.stream.Collectors

Convert a stream to a LinkedHashMap using Collectors.toMap()

import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class StaticReference
{
    public static void main(String[] args)
    {

        List<String> fruits = Arrays.asList("apple", "mango", "pomo", 
                                            "banana", "orange", "apple");

        Map<String, String> collectedFruits = fruits
                .stream()
                .collect(Collectors.toMap(
                        eachFruit -> eachFruit, //KeyMapper
                        eachFruit -> eachFruit, //Value Mapper
                        (first, second) -> first, //Merge function
                        LinkedHashMap::new)); //LinkedHashMap
        collectedFruits.forEach((key, value) -> {
            System.out.println("(" + key + "," + value + ")");
        });

    }
}

Output

(apple,apple)
(mango,mango)
(pomo,pomo)
(banana,banana)
(orange,orange)

I hope you like this article. Thanks for reading and Please leave us a comment below!

Tags :

About the Author

Rajasekar

Hey There, My name is Rajasekar and I am the author of this site. I hope you are liking my tutorials and references. Programming and learning new technologies are my passion. The ultimate idea of this site is to share my knowledge(I am still a learner :)) and help you out!. Please spread your words about us (staticreference.com) and give a thumbs up :) Feel free to contact me for any queries!.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.