Skip to content

Yet another programming solutions log

Sample bits from programming for the future generations.

Technologies Technologies
  • Algorithms and Data Structures
  • Java Tutorials
  • JUnit Tutorial
  • MongoDB Tutorial
  • Quartz Scheduler Tutorial
  • Spock Framework Tutorial
  • Spring Framework
  • Bash Tutorial
  • Clojure Tutorial
  • Design Patterns
  • Developer’s Tools
  • Productivity
  • About
Expand Search Form

Java 8 List to Map

farenda 2016-11-16 0

Very common task is creation of Map from a List of objects. In this post we show how to use Java 8 to convert List to Map using Collectors.

Sample data for processing in collections

This is our sample class that we we’ll use to create mappings:

package com.farenda.java.util;

public class User {
    private static long userCounter;
    private long id;
    private final String name;

    public User(String name) {
        this.id = userCounter++;
        this.name = name;
    }

    public long getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    @Override
    public String toString() {
        return "User(id:" + id + ", name: " + name + ")";
    }
}

Pre Java 8 List to Map

Before Java 8 the standard way to convert List to Map was to use for-each loop like so:

List<User> users = asList(new User("Foo"), new User("Bar"));
Map<String, User> usersByName = new HashMap<>();
for (User user : users) {
    usersByName.put(user.getName(), user);
}
System.out.println("Mapping: " + usersByName);

In the above code we’ve created a mapping from user’s name to user. This is the result:

Mapping: {Bar=User(id:1, name: Bar), Foo=User(id:0, name: Foo)}

Java 8 List to Map using Collector

Since Java 8 there’s a great way to convert List to Map using java.util.stream.Collectors.toMap. There are three versions of this Collector, but here we’ll use the simplest one:

List<User> users = asList(new User("Foo"), new User("Bar"));
Map<String, User> usersByName = users.stream()
    .collect(toMap(User::getName, Function.identity()));
System.out.println("Mapping: " + usersByName);

The toMap Collector takes two functions, both taking User as parameter:

  • the first one should create Map key from the parameter,
  • the second one should create Map value from the parameter.

In the example we use User.getName() to create Map key and Function.identity(), which just returns given parameter as is, to create Map value.

The above code produces the following output:

Mapping: {Bar=User(id:1, name: Bar), Foo=User(id:0, name: Foo)}

References:

  • Check out Java Util Tutorial for more funky Java 8
Share with the World!
Categories Java Tags java, java-collections, java-util, java8
Previous: Java 8 forEach examples
Next: Java 8 count frequency of numbers/elements/objects

Recent Posts

  • Java 8 Date Time concepts
  • Maven dependency to local JAR
  • Caesar cipher in Java
  • Java casting trick
  • Java 8 flatMap practical example
  • Linked List – remove element
  • Linked List – insert element at position
  • Linked List add element at the end
  • Create Java Streams
  • Floyd Cycle detection in Java

Pages

  • About Farenda
  • Algorithms and Data Structures
  • Bash Tutorial
  • Bean Validation Tutorial
  • Clojure Tutorial
  • Design Patterns
  • Java 8 Streams and Lambda Expressions Tutorial
  • Java Basics Tutorial
  • Java Collections Tutorial
  • Java Concurrency Tutorial
  • Java IO Tutorial
  • Java Tutorials
  • Java Util Tutorial
  • Java XML Tutorial
  • JUnit Tutorial
  • MongoDB Tutorial
  • Quartz Scheduler Tutorial
  • Software Developer’s Tools
  • Spock Framework Tutorial
  • Spring Framework

Tags

algorithms bash bean-validation books clojure design-patterns embedmongo exercises git gof gradle groovy hateoas hsqldb i18n java java-basics java-collections java-concurrency java-io java-lang java-time java-util java-xml java8 java8-files junit linux lists log4j logging maven mongodb performance quartz refactoring regex rest slf4j solid spring spring-boot spring-core sql unit-tests

Yet another programming solutions log © 2022

sponsored