List 转 Map (Convert List to Map)

https://www.mkyong.com/java8/java-8-convert-list-to-map/

Java 8 – Convert List to Map

By mkyong | March 19, 2016 | Updated : May 26, 2017 | Viewed : 392,244 | +3,600 pv/w

Few Java 8 examples to show you how to convert a List of objects into a Map, and how to handle the duplicated keys.

Hosting.java

package com.mkyong.java8

public class Hosting {

    private int Id;
    private String name;
    private long websites;

    public Hosting(int id, String name, long websites) {
        Id = id;
        this.name = name;
        this.websites = websites;
    }

    //getters, setters and toString()
}

Copy

1. List to Map – Collectors.toMap()

Create a list of the Hosting objects, and uses Collectors.toMap to convert it into a Map.

TestListMap.java

package com.mkyong.java8

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

public class TestListMap {

    public static void main(String[] args) {

        List<Hosting> list = new ArrayList<>();
        list.add(new Hosting(1, "liquidweb.com", 80000));
        list.add(new Hosting(2, "linode.com", 90000));
        list.add(new Hosting(3, "digitalocean.com", 120000));
        list.add(new Hosting(4, "aws.amazon.com", 200000));
        list.add(new Hosting(5, "mkyong.com", 1));

        // key = id, value - websites
        Map<Integer, String> result1 = list.stream().collect(
                Collectors.toMap(Hosting::getId, Hosting::getName));

        System.out.println("Result 1 : " + result1);

        // key = name, value - websites
        Map<String, Long> result2 = list.stream().collect(
                Collectors.toMap(Hosting::getName, Hosting::getWebsites));

        System.out.println("Result 2 : " + result2);

        // Same with result1, just different syntax
        // key = id, value = name
        Map<Integer, String> result3 = list.stream().collect(
                Collectors.toMap(x -> x.getId(), x -> x.getName()));

        System.out.println("Result 3 : " + result3);
    }
}

Copy

Output

Result 1 : {1=liquidweb.com, 2=linode.com, 3=digitalocean.com, 4=aws.amazon.com, 5=mkyong.com}
Result 2 : {liquidweb.com=80000, mkyong.com=1, digitalocean.com=120000, aws.amazon.com=200000, linode.com=90000}
Result 3 : {1=liquidweb.com, 2=linode.com, 3=digitalocean.com, 4=aws.amazon.com, 5=mkyong.com}

Copy

扫描二维码关注公众号,回复: 5070674 查看本文章

2. List to Map – Duplicated Key!

2.1 Run below code, and duplicated key errors will be thrown!

TestDuplicatedKey.java

package com.mkyong.java8;

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

public class TestDuplicatedKey {

    public static void main(String[] args) {

        List<Hosting> list = new ArrayList<>();
        list.add(new Hosting(1, "liquidweb.com", 80000));
        list.add(new Hosting(2, "linode.com", 90000));
        list.add(new Hosting(3, "digitalocean.com", 120000));
        list.add(new Hosting(4, "aws.amazon.com", 200000));
        list.add(new Hosting(5, "mkyong.com", 1));
		
        list.add(new Hosting(6, "linode.com", 100000)); // new line

        // key = name, value - websites , but the key 'linode' is duplicated!?
        Map<String, Long> result1 = list.stream().collect(
                Collectors.toMap(Hosting::getName, Hosting::getWebsites));

        System.out.println("Result 1 : " + result1);

    }
}

Copy

Output – The error message below is a bit misleading, it should show “linode” instead of the value of the key.

Exception in thread "main" java.lang.IllegalStateException: Duplicate key 90000
	at java.util.stream.Collectors.lambda$throwingMerger$0(Collectors.java:133)
	at java.util.HashMap.merge(HashMap.java:1245)
	//...

Copy

2.2 To solve the duplicated key issue above, pass in the third mergeFunction argument like this :

	Map<String, Long> result1 = list.stream().collect(
                Collectors.toMap(Hosting::getName, Hosting::getWebsites,
                        (oldValue, newValue) -> oldValue
                )
        );

Copy

Output

Result 1 : {..., aws.amazon.com=200000, linode.com=90000}

Copy

Note
(oldValue, newValue) -> oldValue ==> If the key is duplicated, do you prefer oldKey or newKey?

3.3 Try newValue

	Map<String, Long> result1 = list.stream().collect(
                Collectors.toMap(Hosting::getName, Hosting::getWebsites,
                        (oldValue, newValue) -> newvalue
                )
        );

Copy

Output

Result 1 : {..., aws.amazon.com=200000, linode.com=100000}

Copy

3. List to Map – Sort & Collect

TestSortCollect.java

package com.mkyong.java8;

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

public class TestSortCollect {

    public static void main(String[] args) {

        List<Hosting> list = new ArrayList<>();
        list.add(new Hosting(1, "liquidweb.com", 80000));
        list.add(new Hosting(2, "linode.com", 90000));
        list.add(new Hosting(3, "digitalocean.com", 120000));
        list.add(new Hosting(4, "aws.amazon.com", 200000));
        list.add(new Hosting(5, "mkyong.com", 1));
        list.add(new Hosting(6, "linode.com", 100000));

        //example 1
        Map result1 = list.stream()
                .sorted(Comparator.comparingLong(Hosting::getWebsites).reversed())
                .collect(
                        Collectors.toMap(
                                Hosting::getName, Hosting::getWebsites, // key = name, value = websites
                                (oldValue, newValue) -> oldValue,       // if same key, take the old key
                                LinkedHashMap::new                      // returns a LinkedHashMap, keep order
                        ));

        System.out.println("Result 1 : " + result1);

    }
}

Copy

Output

Result 1 : {aws.amazon.com=200000, digitalocean.com=120000, linode.com=100000, liquidweb.com=80000, mkyong.com=1}

Copy

P.S In above example, the stream is sorted before collect, so the “linode.com=100000” became the ‘oldValue’.

References

  1. Java 8 Collectors JavaDoc
  2. Java 8 – How to sort a Map
  3. Java 8 Lambda : Comparator example

collectors duplicated key java 8 list map sort stream

HOW MUCH DO YOU KNOW ABOUT ROBOTS?

  

How was the first working robot employed in 1961?

The word robot comes from the Czech word 'robota', which means:

There are ~4,000 robots serving in the US army, including ones that:

This first humanoid robot was 7 feet tall and could 'speak' 700 words.

In the United Arab Emirates, robot jockeys are often used:

The robot rock band that features a 78-fingered guitarist is called:

Who sketched 'mechanical knights' as early as 1945?

In which country did Barack Obama play game of soccer against a robot?

Spirit and Opportunity refer to which robots?

The first case of robot homicide occured when:

15

  • Searching for gold

  • Spying on Russian-American families

  • Watering at the Olive Garden

  • Making cars for Ford

  • Machinery

  • Superhuman

  • Fake friend

  • Drudgery

  • Attack soldiers as part of training

  • Teach soldiers foreign languages

  • Detect roadside bombs

  • Prepare coffee for officers

  • Electra

  • Apollo

  • Dollie

  • Simon

  • To find hidden oil wells

  • As moving jukeboxes in bars

  • To clear land mines

  • Instead of humans for camel racing

  • Mind over Body

  • Best of Bionic

  • Heavy and Metal

  • Z-Machines

  • The Wright Brother

  • Thomas Edison

  • Henry Ford

  • Leonardo Da Vinchi

  • Thailand

  • Brazil

  • Japan

  • England

  • The first pair of Google cars

  • The 'bots that uncovered Bin Laden

  • The first mobile Japanese robot

  • Drones made to explore Mars

  • A robot combusted, killing 2 engineers

  • A Google car ran over a pedestrian

  • A robotic arm crushed a factory worker

  • A hacked NASA robot went rogue

You Scored A Fair

5/10

CHALLENGE

YOUR FRIENDS

NEXT QUIZ STARTS IN:

10

 Your Score 0 Question 1/10

Add This Widget To Your Site

Sponsored

Advertisement

About the Author

author image

mkyong

Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.

猜你喜欢

转载自blog.csdn.net/lppl010_/article/details/86600624