2016년 12월 2일 금요일

Java List convert to Map

You can convert list to map by using java collector.

- JpaApplication.java

package org.blog.test;

import lombok.extern.slf4j.Slf4j;
import org.blog.test.user.entity.User;
import org.blog.test.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

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

@SpringBootApplication
@Slf4j
public class JpaApplication implements CommandLineRunner {
    public static void main(String[] args) {
        SpringApplication.run(JpaApplication.class, args);
    }

    @Autowired
    private UserService userService;

    @Override
    public void run(String... args) throws Exception {

        List users = new ArrayList<>();
        users.add(new User(1L, "name1"));
        users.add(new User(2L, "name2"));
        users.add(new User(3L, "name3"));

        Map userMap = users.stream().collect(Collectors.toMap(x -> x.getId(), x -> x));

        log.info("userMap : [{}]", userMap);

    }
}

- result

2016-12-03 03:04:49.178  INFO 6344 --- [           main] org.blog.test.JpaApplication             : userMap : [{1=User(id=1, name=name1), 2=User(id=2, name=name2), 3=User(id=3, name=name3)}]

댓글 없음 :

댓글 쓰기