Languages
[Edit]
EN

Java 8 - convert list of objects to map (from List<User> to Map<Long, User> - long to object / counter)

7 points
Created by:
Wallace
636

Quick solution - using simple lambda:

List<User> users = Arrays.asList(new User(1, "Ann"), new User(2, "Tom"));

Map<Long, User> usersMap = users.stream().collect(
        Collectors.toMap(User::getUserId, user -> user));

// {1=User{userId=1, name='Ann'}, 2=User{userId=2, name='Tom'}}
System.out.println(usersMap);

 

Quick solution 2 - using Function.identity():

List<User> users = Arrays.asList(new User(1, "Ann"), new User(2, "Tom"));

Map<Long, User> usersMap2 = users.stream().collect(
        Collectors.toMap(User::getUserId, Function.identity()));

// {1=User{userId=1, name='Ann'}, 2=User{userId=2, name='Tom'}}
System.out.println(usersMap2);

 

Full example:

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

public class Example {

    public static void main(String[] args) {

        List<User> users = Arrays.asList(new User(1, "Ann"), new User(2, "Tom"));

        // example 1 with lambda
        Map<Long, User> usersMap = users.stream().collect(
                Collectors.toMap(User::getUserId, user -> user));

        // {1=User{userId=1, name='Ann'}, 2=User{userId=2, name='Tom'}}
        System.out.println(usersMap);

        // example 2 with Function.identity()
        Map<Long, User> usersMap2 = users.stream().collect(
                Collectors.toMap(User::getUserId, Function.identity()));

        // {1=User{userId=1, name='Ann'}, 2=User{userId=2, name='Tom'}}
        System.out.println(usersMap2);
    }

    private static class User {
        private final long userId;
        private final String name;

        public User(long userId, String name) {
            this.userId = userId;
            this.name = name;
        }

        public long getUserId() {
            return userId;
        }

        public String getName() {
            return name;
        }

        @Override
        public String toString() {
            return "User{" +
                    "userId=" + userId +
                    ", name='" + name + '\'' +
                    '}';
        }
    }
}

 

Alternative titles

  1. Java 8 - convert list of objects to map (int or long to object - counter)
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

Java 8 - stream API examples

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join