์ ๋ ฌํด๋ `List`๋ฅผ ` Collectors.toMap()`์ผ๋ก ์ค๋ณต ์ ๊ฑฐ ํ ๋ค์ `List`๋ก ๋ง๋ค์๋๋ ์์๊ฐ ์ํค๋ ๋ฌธ์ ๊ฐ ๋ฐ์ํ๋ค.
๊ตฌ๊ธ๋ง ํ ๊ฒฐ๋ก ์ `Collectors.toMap()`์ ๊ธฐ๋ณธ์ ์ผ๋ก `HashMap`์ ์ฌ์ฉํ๊ธฐ ๋๋ฌธ์ ์์๋ฅผ ์์ด๋ฒ๋ฆฐ๋ค.
`LinkedHashMap::new`๋ก ์์งํ๋ฉด ์์๊ฐ ๊ทธ๋๋ก ์ ์ง๋๋ค.
๐ฅ ๊ธฐ์กด์ ์ฌ์ฉํ๋ ์ฝ๋
List<User> userList = // ID ๊ธฐ์ค ์ค๋ฆ์ฐจ์ ์ ๋ ฌ๋์ด ์๋ค๊ณ ๊ฐ์
List<User> result = userList.stream()
.collect(Collectors.collectingAndThen(
Collectors.toMap(User::uniqueKey, Function.identity(), (exist, repl) -> exist),
map -> new ArrayList<>(map.values())
));
System.out.println(result.stream().map(User::getId).collect(Collectors.toList()));
- ๊ธฐ๋: ์๋ณธ `userList` ์์ (1, 2, 3, ... , 10, 12, 13, ...)
- ์ค์ : ID ์์๊ฐ ํ์ด์ง๊ฑฐ๋, ๊ฒฝ์ฐ์ ๋ฐ๋ผ ๋๋ฝ/์ค๋ณต์ด ๋ฐ์
๐ค ์์๊ฐ ๊นจ์ง๋ ์ด์
๊ตฌํ์ฒด | ํน์ง |
HashMap (๊ธฐ๋ณธ) | ํค/๊ฐ ์กฐํ O / ์ฝ์ ์์ ๋ณด์ฅ X |
LinkedHashMap | ํค/๊ฐ ์กฐํ O / ์ฝ์ ์์ ๋ณด์ฅ O |
`Collectors.toMap()` โก `new HashMap<>()` ์ฌ์ฉ โก `values()`๋ฅผ ๊บผ๋ผ ๋ ๋ด๋ถ ๋ฐฐ์ด ์์๋ฅผ ์๋ก ์ ๋ ฌํด์ ์ฝ์ ์์ ์ ์ง ์คํจ
โป Java 8 ์ดํ์๋ ๊ธฐ๋ณธ Map์ ์ฌ์ ํ `HashMap`์ด๋ผ๊ณ ํ๋ค.
โจ ํด๊ฒฐ ๋ฐฉ๋ฒ: `LinkedHashMap` ์ง์
List<User> result = userList.stream()
.collect(Collectors.collectingAndThen(
Collectors.toMap(
User::uniqueKey, // key mapper
Function.identity(), // value mapper
(exist, repl) -> exist, // ์ค๋ณต key ์ ์ฑ
: ๊ธฐ์กด๊ฐ ์ ์ง
LinkedHashMap::new // โญ๏ธ ์์ ์ ์ง Map ์์ฑ
),
map -> new ArrayList<>(map.values())
));
- ์คํ ๊ฒฐ๊ณผ: ์๋ณธ `userList` ์์ (1, 2, 3, ... , 10, 11, 12, ...)