5
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

List<T> を IDをキーにしたMap に変換

Last updated at Posted at 2015-11-17

すぐ忘れるのでメモ。

idが重複するとjava.lang.IllegalStateException: Duplicate keyが発生するので注意。

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


public class ListToMapSample {
	public static void main(String[] args) {
		List<Foo> fooList = new ArrayList<>();
		fooList.add(new Foo(123, "aiueo"));
		fooList.add(new Foo(234, "ateawgareg"));
		fooList.add(new Foo(456, "faaewfgwaiaef"));
		
		Map<Integer, Foo> map = fooList.stream()
				.collect(Collectors.toMap(Foo::getId, UnaryOperator.identity()));
		System.out.println(map);
	}
	
	private static class Foo {
		private int id;
		private String name;
		public Foo(int id, String name) {
			this.id = id;
			this.name = name;
		}
		
		public int getId() {
			return id;
		}
		
		public String toString() {
			return "{id:" + id + ", name:" + name + "}";
		}
	}
}

{456={id:456, name:faaewfgwaiaef}, 234={id:234, name:ateawgareg}, 123={id:123, name:aiueo}}
5
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?