您好,登錄后才能下訂單哦!
這篇文章主要介紹了如何在Java8中將List<T>轉(zhuǎn)為Map<String,T>,此處通過實例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考價值,需要的朋友可以參考下:
Java是一門面向?qū)ο缶幊陶Z言,可以編寫桌面應(yīng)用程序、Web應(yīng)用程序、分布式系統(tǒng)和嵌入式系統(tǒng)應(yīng)用程序。
public class AnswerApp { public static void main(String[] args) throws Exception { List<String> names = Lists.newArrayList("Answer", "AnswerAIL", "AI"); Map<String, Integer> map = names.stream().collect(Collectors.toMap(v -> v, v -> 1)); System.out.println(map); } }
程序運行輸出
{Answer=1, AnswerAIL=1, AI=1}
public static void main(String[] args) throws Exception { List<User> users = new ArrayList<>(); for (int i = 0; i < 3; i++) { users.add(new User("answer" + i, new Random().nextInt(100))); } System.out.println(JSON.toJSONString(users)); System.out.println(); Map<String, Integer> map = users.stream().collect(Collectors.toMap(User::getName, User::getAge)); System.out.println(map); }
程序運行輸出
[{"age":78,"name":"answer0"},{"age":89,"name":"answer1"},{"age":72,"name":"answer2"}] {answer2=72, answer1=89, answer0=78}
實現(xiàn)方式1
public class AnswerApp { public static void main(String[] args) throws Exception { List<User> users = new ArrayList<>(); for (int i = 0; i < 3; i++) { // 改為此代碼, 轉(zhuǎn)map時會報錯 Duplicate key User // users.add(new User("answer", new Random().nextInt(100))); users.add(new User("answer" + i, new Random().nextInt(100))); } System.out.println(JSON.toJSONString(users)); System.out.println(); Map<String, User> map = users.stream().collect(Collectors.toMap(User::getName, Function.identity())); System.out.println(JSON.toJSONString(map)); } }
該方式如果 map 的 key(如上述例子的 User::getName 的值) 重復(fù), 會拋錯java.lang.IllegalStateException: Duplicate key User
程序運行輸出
[{"age":22,"name":"answer0"},{"age":79,"name":"answer1"},{"age":81,"name":"answer2"}] {"answer2":{"age":81,"name":"answer2"},"answer1":{"age":79,"name":"answer1"},"answer0":{"age":22,"name":"answer0"}}
實現(xiàn)方式2
public class AnswerApp { public static void main(String[] args) throws Exception { List<User> users = new ArrayList<>(); for (int i = 0; i < 3; i++) { users.add(new User("answer", new Random().nextInt(100))); } System.out.println(JSON.toJSONString(users)); System.out.println(); // 如果 key 重復(fù), 則根據(jù) 沖突方法 ·(key1, key2) -> key2· 判斷. 解釋: key1 key2 沖突時 取 key2 Map<String, User> map = users.stream().collect(Collectors.toMap(User::getName, Function.identity(), (key1, key2) -> key2)); System.out.println(JSON.toJSONString(map)); } }
程序運行輸出
[{"age":24,"name":"answer"},{"age":89,"name":"answer"},{"age":68,"name":"answer"}] {"answer":{"age":68,"name":"answer"}}
如果改為 (key1, key2) -> key1 則輸出 {"answer":{"age":24,"name":"answer"}}
User 實體
@Data @NoArgsConstructor @AllArgsConstructor public class User { private Long id; private String name; private Integer age; public User(String name) { this.name = name; } public User(String name, Integer age) { this.name = name; this.age = age; } }
補(bǔ)充:java8中使用Lambda表達(dá)式將list中實體類的兩個字段轉(zhuǎn)Map
代碼:
List<Entity> list = new ArrayList<>(); Map<Integer, String> map = list.stream().collect(Collectors.toMap(Entity::getId, Entity::getType));
** * List -> Map * 需要注意的是: * toMap 如果集合對象有重復(fù)的key,會報錯Duplicate key .... * apple1,apple12的id都為1。 * 可以用 (k1,k2)->k1 來設(shè)置,如果有重復(fù)的key,則保留key1,舍棄key2 */ Map<Integer, Apple> appleMap = appleList.stream().collect(Collectors.toMap(Apple::getId, a -> a,(k1,k2)->k1)); 安照某一字段去重 list = list.stream().filter(distinctByKey(p -> ((ModCreditColumn) p).getFieldCode())).collect(Collectors.toList()); List<Double> unitNetValue = listIncreaseDto.stream().map(IncreaseDto :: getUnitNetValue).collect(Collectors.toList()); //求和 對象List BigDecimal allFullMarketPrice = entityList.stream().filter(value -> value.getFullMarketPrice()!= null).map(SceneAnalysisRespVo::getFullMarketPrice).reduce(BigDecimal.ZERO, BigDecimal::add); List<BigDecimal> naturalDayList; BigDecimal total = naturalDayList.stream().reduce(BigDecimal.ZERO, BigDecimal::add); 分組函數(shù) Map<String, List<SceneAnalysisRespVo>> groupMap = total.getGroupList().stream().collect(Collectors.groupingBy(SceneAnalysisRespVo::getVmName)); //DV01之和 BigDecimal allDV01 = values.stream().filter(sceneAnalysisRespVo -> sceneAnalysisRespVo.getDv() != null).map(SceneAnalysisRespVo::getDv).reduce(BigDecimal.ZERO, BigDecimal::add);
到此這篇關(guān)于如何在Java8中將List<T>轉(zhuǎn)為Map<String,T>的文章就介紹到這了,更多相關(guān)如何在Java8中將List<T>轉(zhuǎn)為Map<String,T>的內(nèi)容請搜索億速云以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持億速云!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。