How to convert a list to a map with a set value in java 8

2594 views java-8
8

  List<Hosting> list = new ArrayList<>();
  list.add(new Hosting(1, "liquidweb.com"));
  list.add(new Hosting(2, "aws.amazon.com"));
  list.add(new Hosting(3, "digitalocean.com"));
  list.add(new Hosting(2, "aws.amazon.com"));

I want to convert the above list into a Map>

1 -> "liquidweb.com"
2 -> "aws.amazon.com"
3 -> "digitalocean.com"

How can I do the conversion in Java 8

answered question

2 Answers

1

list.stream().collect(toMap(e -> e.getId(), mapping(e -> e.getValue(), toSet())));

posted this
6

By using java-8 stream API

Map<Integer, String> result1 = list.stream().collect(
            Collectors.toMap(Hosting::getId, Hosting::getName));

posted this

Have an answer?

JD

Please login first before posting an answer.