欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Java實現(xiàn)List轉(zhuǎn)換為Map的方法小結(jié)

 更新時間:2024年03月27日 11:15:29   作者:princeAladdin  
這篇文章主要為大家詳細(xì)介紹了Java實現(xiàn)List轉(zhuǎn)換為Map的一些常見的方法,文中的示例代碼講解詳細(xì),具有一定的借鑒價值,有需要的小伙伴可以參考一下

一、List轉(zhuǎn)換為Map

示例:代碼案例

public class People (
	private Integer id;
	private String name;
	private Integer age
	private String address;
	//TODO 構(gòu)造方法和get和set方法省略
)
final static List<People> peopleList = new ArrayList<People>();


 // 初始化集合數(shù)據(jù)

static {
   People p1 = new People(0001, "張三", 12, "江蘇南京");
   People p2 = new People(0002, "李四", 14, "上海");
   People p3 = new People(0003, "王二", 11, "浙江臺州");
   People p4 = new People(0004, "李五", 12, "河南鄭州");

   peopleList.add(p1);
   peopleList.add(p2);
   peopleList.add(p3);
   peopleList.add(p4);
}

1.1、List轉(zhuǎn)化為Map<Integer,String>

Map<Integer, String> map = peopleList.stream().collect(Collectors.toMap
(People::getId, People::getAddress, (value1, value2) -> value1));

1.2 、List轉(zhuǎn)化為Map<Integer,Object>

Map<Integer, People> map = peopleList.stream().collect(Collectors.toMap
(People::getId, each -> each, (value1, value2) -> value1));

1.3、List轉(zhuǎn)化為Map<Integer,List>

Map<Integer, List<People>> map = peopleList.stream().collect(Collectors
.groupingBy(People::getId));

1.4 List轉(zhuǎn)化為Map<Integer,List>

Map<Integer, List<String>> map3 = peopleList.stream().collect(Collectors.
toMap(People::getId, each -> Collections.singletonList(each.getName()), 
(value1, value2) -> {
            List<String> union = new ArrayList<>(value1);
            union.addAll(value2);
            return union;
}));

1.5、 List<Map<String,Object>> 轉(zhuǎn)化為Map<String,Object>

final static List<Map<String, Object>> mapStudentList = new ArrayList<>();
public static void main(String[] args) {
		Map<String, Object> map4 = mapStudentList.stream().collect(Collectors.toMap(each -> Objects.toString(each.get("id"), ""), each -> each.get("student"), (key1, key2) -> key1));
	}


	/**
	 * 初始化集合數(shù)據(jù)
	 */
	static {
		Student stu1 = new Student("0001", "張三", 12, "江蘇南京");
		Student stu2 = new Student("0002", "李四", 14, "江蘇無錫");
		Student stu3 = new Student("0003", "王二", 11, "浙江臺州");
		Student stu4 = new Student("0004", "李五", 12, "浙江溫州");


		Map<String, Object> map1 = new HashMap<>();
		map1.put("id", "0001");
		map1.put("student", stu1);

		Map<String, Object> map2 = new HashMap<>();
		map2.put("id", "0002");
		map2.put("student", stu2);

		Map<String, Object> map3 = new HashMap<>();
		map3.put("id", "0003");
		map3.put("student", stu3);

		Map<String, Object> map4 = new HashMap<>();
		map4.put("id", "0004");
		map4.put("student", stu4);

		mapStudentList.add(map1);
		mapStudentList.add(map2);
		mapStudentList.add(map3);
		mapStudentList.add(map4);
	}

1.6、List<Map<String,String>> 轉(zhuǎn)化為Map<String,Map<String,String>>

    final static List<Map<String, String>> listMapList = new ArrayList<>();


	public static void main(String[] args) {
		Map<String, Map<String, String>> map5 = listMapList.stream().collect(Collectors.toMap(each -> each.get("id"), each -> each, (key1, key2) -> key1));
		System.out.println("map5 = " + map5);

	}

	/**
	 * 初始化集合數(shù)據(jù)
	 */
	static {
		Map<String, String> map1 = new HashMap<>();
		map1.put("id", "0001");
		map1.put("name", "張三");
		map1.put("age", "12");
		map1.put("address", "江蘇南京");

		Map<String, String> map2 = new HashMap<>();
		map2.put("id", "0002");
		map2.put("name", "李四");
		map2.put("age", "14");
		map2.put("address", "江蘇無錫");


		Map<String, String> map3 = new HashMap<>();
		map3.put("id", "0003");
		map3.put("name", "王二");
		map3.put("age", "11");
		map3.put("address", "浙江臺州");

		Map<String, String> map4 = new HashMap<>();
		map4.put("id", "0004");
		map4.put("name", "李五");
		map4.put("age", "12");
		map4.put("address", "浙江溫州");


		listMapList.add(map1);
		listMapList.add(map2);
		listMapList.add(map3);
		listMapList.add(map4);
	}

1.7、List<Map<String,String>> 轉(zhuǎn)化為Map<String,String>

     final static List<Map<String, String>> listmapstringlist = new ArrayList<>();

	 public static void main(String[] args) {
     Map<String, String> map6 = listmapstringlist.stream().collect(Collectors.toMap(each -> each.get("id"), each -> each.get("name"), (key1, key2) -> key1));

	}

	/**
	 * 初始化集合數(shù)據(jù)
	 */
	static {
		Map<String, String> map1 = new HashMap<>();
		map1.put("id", "0001");
		map1.put("name", "張三");
		map1.put("age", "12");
		map1.put("address", "江蘇南京");

		Map<String, String> map2 = new HashMap<>();
		map2.put("id", "0002");
		map2.put("name", "李四");
		map2.put("age", "14");
		map2.put("address", "江蘇無錫");


		Map<String, String> map3 = new HashMap<>();
		map3.put("id", "0003");
		map3.put("name", "王二");
		map3.put("age", "11");
		map3.put("address", "浙江臺州");

		Map<String, String> map4 = new HashMap<>();
		map4.put("id", "0004");
		map4.put("name", "李五");
		map4.put("age", "12");
		map4.put("address", "浙江溫州");
		listmapstringlist.add(map1);
		listmapstringlist.add(map2);
		listmapstringlist.add(map3);
		listmapstringlist.add(map4);
	}
 list.add("c");
    list.add("a");
    list.add("b");
    list.add("d");

    List<User> userList = new ArrayList<>();
    userList.add(new User(new Long(1),"李世民","123lsm@163.com","男","110"));
    userList.add(new User(new Long(2),"宇文成都","123ywcd@163.com","男","111"));
    userList.add(new User(new Long(3),"裴元慶","123pyq@163.com","男","112"));
    userList.add(new User(new Long(4),"程咬金","123cyj@163.com","男","113"));
    userList.add(new User(new Long(5),"李元霸","123lyb@163.com","男","114"));
    userList.add(new User(new Long(6),"瀟美娘","123xmn@163.com","女","11q"));
    userList.add(new User(new Long(6),"瀟美娘","123xmn@163.com","女","11q"));



    for (int i = 0; i < list.size(); i++) {
        System.out.println("第一種遍歷list方法" + list.get(i));
    }

    for (String s : list) {
        System.out.println("第二種遍歷list方法:" + s);
    }

    Iterator<String> iterator = list.iterator();
    while (iterator.hasNext()) {
        System.out.println("第三種遍歷list方法:" + iterator.next());
    }

    list.forEach(new Consumer<String>() {
        @Override
        public void accept(String s) {
            System.out.printf("第四種遍歷list方法:" + s + "\n");
        }
    });

    List<User> userList1 = new ArrayList<>();
    User user1 = new User();
    userList.forEach(user -> {
        user1.setId(user.getId());
        user1.setUserName(user.getUserName());
        user1.setSex(user.getSex());
        user1.setPhone(user.getPhone());
        user1.seteMail(user.geteMail());
        userList1.add(user1);
        System.out.println("第五種遍歷方法########:"+userList1);

    });


    List<User> mm = userList.stream().filter(user -> user.getSex().equals("男")).collect(Collectors.toList());
    System.out.println("第六種:過濾掉不想要的列表,留下想要的列表########:");
    mm.forEach(System.out::println);

    List<String> gg = userList.stream().map(User::getSex).distinct().collect(Collectors.toList());
    System.out.println("=========gg對某個字段去重!");
    gg.forEach(System.out::println);

    List<String> g = userList.stream().map(user -> user.getUserName()).distinct().collect(Collectors.toList());
    System.out.println("=========g對某個字段去重!");
    g.forEach(System.out::println);

    List<User> users = userList.stream().distinct().collect(Collectors.toList());
    System.out.println("去除完全重復(fù)的數(shù)據(jù)!");
    users.forEach(System.out::println);

    ArrayList<User> arrayList = userList.stream().collect(Collectors.collectingAndThen(Collectors
            .toCollection(() -> new TreeSet<>(Comparator.comparing(user -> user.getSex()))), ArrayList::new));
    System.out.println("arrayList根據(jù)指定的字段去除重復(fù)的數(shù)據(jù)");
    arrayList.forEach(System.out::println);


    List<Map<String,String>> mapList = new ArrayList<>();
    Map<String,String> mapL = new HashMap<>();
    Map<String,String> mapL2 = new HashMap<>();
    mapL.put("a","李世民");
    mapL.put("b","李元霸");
    mapL.put("c","秦叔寶");
    mapL2.put("a","李世民");
    mapList.add(mapL);
    mapList.add(mapL2);
    ArrayList<Map<String, String>> mapArrayList = mapList.stream().collect(Collectors.collectingAndThen(Collectors
            .toCollection(() -> new TreeSet<>(Comparator.comparing(map -> map.get("a")))), ArrayList::new));
    System.out.println("根據(jù)list集合中某個對象里的字段值去重:"+mapArrayList);

    /*
    * findAny和findFirst都是獲取第一條信息,如果未找到則返回null
    * */
    User orElse = userList.stream().filter(user -> user.getUserName().equals("瀟美娘")).findAny().orElse(null);
    System.out.println("獲取存在瀟美娘的第一條用戶信息orElse:"+orElse);

    User anElse = userList.stream().filter(user -> user.getUserName().equals("羅成")).findFirst().orElse(null);
    System.out.println("獲取不存在羅成的第一條用戶信息anElse:"+anElse);

    System.out.println("下面介紹下map=========歡迎來到map家族!");

    Map<String, Integer> map = new HashMap<>();
    map.put("e", 2);
    map.put("h", 1);
    map.put("g", 9);
    map.put("f", 6);
    for (Map.Entry<String, Integer> m : map.entrySet()) {
        System.out.println("第一種map集合遍歷:" + "KEY:" + m.getKey() + "\t" + "VALUE:" + m.getValue());
    }

    for (String key : map.keySet()) {
        System.out.println("第二種map集合遍歷:" + "KEY:" + key + "\t" + "VALUE:" + map.get(key));
    }

    Iterator<Map.Entry<String, Integer>> iterator1 = map.entrySet().iterator();
    while (iterator1.hasNext()) {
        Map.Entry<String, Integer> entry = iterator1.next();
        System.out.println("第三種map集合遍歷:" + "KEY:" + entry.getKey() + "\t" + "VALUE:" + entry.getValue());
    }
    map.forEach(new BiConsumer<String, Integer>() {
        @Override
        public void accept(String s, Integer s2) {
            System.out.println("第四種map集合遍歷:" + "KEY:" + s + "\t" + "VALUE:" + s2);

        }
    });

    map.entrySet().forEach(entry -> System.out.println("第五種map集合遍歷:" + "KEY:" + entry.getKey() + "\t" + "VALUE:" + entry.getValue()));

    map.values().forEach(s -> {
        System.out.println("直接獲取map中的所有VALUE" + s);
    });

    map.forEach((k, v) -> {
        System.out.println("第六種最好的方法map集合遍歷:" + "KEY:" + k + "\t" + "VALUE:" + v);
    });


    HashMap<String,Integer> maps = map.entrySet().stream().sorted((o1, o2) -> o1.getValue().compareTo(o2.getValue()))
            .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (o1, o2) -> o1, LinkedHashMap::new));
    maps.forEach((k,v)->System.out.println("對maps集合中value數(shù)據(jù)升序排序:"+"k:"+k+"\t"+"v:"+v));

    HashMap<String,Integer> mapsS = map.entrySet().stream().sorted((o1, o2) -> o2.getValue().compareTo(o1.getValue()))
            .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (o1, o2) -> o2, LinkedHashMap::new));
    mapsS.forEach((k,v)->System.out.println("對mapsS集合中value數(shù)據(jù)降序排序:"+"k:"+k+"\t"+"v:"+v));

    HashMap<String,Integer> map0 = map.entrySet().stream().sorted((Map.Entry.comparingByValue()))
            .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (o1, o2) -> o1, LinkedHashMap::new));
    map0.forEach((k,v)->System.out.println("對map0集合中value數(shù)據(jù)升序排序:" + "k:"+k+"\t"+"v:"+v));

    HashMap<String,Integer> map1 = map.entrySet().stream().sorted(Map.Entry.<String,Integer>comparingByKey().reversed())
            .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (o1, o2) -> o1, LinkedHashMap::new));
    map1.forEach((k,v)-> System.out.println("對map1集合中key降序排序:" + "k:"+k+"\t"+"v:"+v));

    HashMap<String,Integer> map2 = map.entrySet().stream().sorted(Map.Entry.<String,Integer>comparingByValue().reversed())
            .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (o1, o2) -> o1, LinkedHashMap::new));
    map2.forEach((k,v)-> System.out.println("對map集合中value降序排序:" + "k:"+k+"\t"+"v:"+v));


}
@Data
public class TestDemo {
 
    //獲取第pageNum頁數(shù)據(jù)
    public static List<?> partition(ArrayList<?> list, int pageSize, int pageNum) {
        //將List按照pageSize拆分成多個List
        List<? extends List<?>> partition = Lists.partition(list, pageSize);
        //總頁數(shù)
        int pages = partition.size();
        pageNum = pageNum <= 0 ? 0 : (pageNum <= (pages - 1) ? pageNum-1 : (pages - 1));
        return partition.get(pageNum);
    }
 
    public static void main(String[] args) {
        List<TestDemo> list = new ArrayList<>();
        list.add(new TestDemo(1L,11L,100L));
        list.add(new TestDemo(2L,11L,600L));
        list.add(new TestDemo(3L,33L,333L));
        list.add(new TestDemo(4L,33L,null));
        list.add(new TestDemo(5L,44L,null));
        //(一、轉(zhuǎn)Map)如果有重復(fù)的key,則保留key1,舍棄key2
        Map<Long, TestDemo> map = list.stream().collect(Collectors.toMap(TestDemo::getId, item -> item, (key1, key2) -> key1));
 
        //(二、排序)
        // Comparator.comparing(類::屬性一).reversed(); 得到排序結(jié)果后再排序
        //Comparator.comparing(類::屬性一,Comparator.reverseOrder());是直接進行排序
        //升序、空值排在最前面、reversed反轉(zhuǎn)排序
        List<TestDemo> sortList = list.stream().sorted(
                Comparator.comparing(TestDemo::getTotal, Comparator.nullsFirst(Long::compareTo)).reversed()
        ).collect(Collectors.toList());
        //屬性一升序,屬性二降序
        sortList = list.stream().sorted(
                Comparator.comparing(TestDemo::getId).thenComparing(TestDemo::getGroup, Comparator.reverseOrder())
        ).collect(Collectors.toList());
 
        //(三、分組)
        Map<Long, List<TestDemo>> groupMapList = list.stream().collect(Collectors.groupingBy(TestDemo::getGroup));
        Map<Long, TestDemo> groupMapObject = list.stream().collect(
                //取分組中的一條數(shù)據(jù)
                Collectors.groupingBy(TestDemo::getGroup, Collectors.collectingAndThen(Collectors.toList(), item -> item.get(0)))
        );
        //分組求和得到新集合
        List<TestDemo> groupSumList = new ArrayList<>();
        list.parallelStream().collect(Collectors.groupingBy(TestDemo::getGroup, Collectors.toList()))
                .forEach((id, groupList) -> {
                    groupList.stream().reduce(
                            (a, b) ->  new TestDemo(a.getId(), a.getGroup(), a.getTotal(), b.getTotal())
                    ).ifPresent(groupSumList::add);
                });
 
        //(四、去重)
        List<String> stringList = new ArrayList<String>() {{ add("A"); add("A"); add("B"); add("B"); add("C"); }};
        stringList = stringList.stream().distinct().collect(Collectors.toList());
        //對象屬性去重
        List<TestDemo>  distinctList = list.stream().collect(
                Collectors.collectingAndThen(Collectors.toCollection(()
                        -> new TreeSet<>(Comparator.comparing(TestDemo::getGroup))), ArrayList::new));
 
        //(五、提取)
        List<Long> groupNumList = list.stream()
            .map(TestDemo::getGroup) //流轉(zhuǎn)化為Long
            .distinct() //去重
            .collect(Collectors.toList());
 
        //(六、過濾)
        List<TestDemo> filterList = list.stream().filter(item -> item.getTotal() != null && item.getTotal() < 200).collect(Collectors.toList());
        List<TestDemo> filtersList = list.stream()
                .filter(item -> {//多條件過濾
                    if(item.getTotal() == null) {
                        return false;
                    }
                    if (item.getTotal() > 200 && item.getTotal() < 400) {
                        return true;
                    }
                    return false;
                }).collect(Collectors.toList());
 
        //(七、取值)
        // 平均數(shù)
        Double avg1 = list.stream().filter(item -> item.getTotal() != null).mapToLong(TestDemo::getTotal).average().orElse(0);//為空的不參與計算
        Double avg2 = list.stream().filter(item -> {
            if(item.getTotal() == null) { //為空的參與計算
                item.setTotal(0L);//避免計算時報空指針錯誤
            }
            return true;
        }).collect(Collectors.averagingLong(TestDemo::getTotal));
        // 最大值
        Long max = list.stream().mapToLong(TestDemo::getTotal).max().orElse(0);
        // 最小值
        Long min = list.stream().mapToLong(TestDemo::getTotal).min().orElse(0);
        //求和
        Long sum = list.stream().mapToLong(TestDemo::getTotal).sum();
    }
 
    private Long id;
    private Long group;
    private Long total;
    public TestDemo(){}
 
    public TestDemo(Long id, Long group, Long total) {
        this.id = id;
        this.group = group;
        this.total = total;
    }
 
    public TestDemo(Long id, Long group, Long aTotal, Long bTotal) {
        this.id = id;
        this.group = group;
        this.total = (aTotal==null ? 0 : aTotal) + (bTotal==null ? 0 : bTotal);
    }
}

以上就是Java實現(xiàn)List轉(zhuǎn)換為Map的方法小結(jié)的詳細(xì)內(nèi)容,更多關(guān)于Java List轉(zhuǎn)Map的資料請關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

  • Java實現(xiàn)將枚舉類轉(zhuǎn)為json并返回給前端

    Java實現(xiàn)將枚舉類轉(zhuǎn)為json并返回給前端

    這篇文章主要為大家詳細(xì)介紹了Java實現(xiàn)將枚舉類轉(zhuǎn)為json并返回給前端的相關(guān)知識,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下
    2023-12-12
  • 命令提示符編譯java的方法(必看篇)

    命令提示符編譯java的方法(必看篇)

    下面小編就為大家?guī)硪黄钐崾痉幾gjava的方法(必看篇)。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2017-05-05
  • 深入詳解java高并發(fā)熱點數(shù)據(jù)更新

    深入詳解java高并發(fā)熱點數(shù)據(jù)更新

    這篇文章主要為大家深入介紹了java高并發(fā)熱點數(shù)據(jù)更新詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2023-04-04
  • SpringMVC全局異常處理小結(jié)

    SpringMVC全局異常處理小結(jié)

    在開發(fā)中,不管是dao層、service層還是controller層,都有可能拋出異常,在springmvc中,能將所有類型的異常處理從各處理過程解耦出來,既保證了相關(guān)處理過程的功能較單一,也實現(xiàn)了異常信息的統(tǒng)一處理和維護,本文介紹SpringMVC全局異常處理,感興趣的朋友一起看看吧
    2024-03-03
  • mybatis如何封裝List<String>類型屬性

    mybatis如何封裝List<String>類型屬性

    這篇文章主要介紹了mybatis如何封裝List<String>類型屬性問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2023-12-12
  • MyBatis-Plus通過插件將數(shù)據(jù)庫表生成Entiry,Mapper.xml,Mapper.class的方式

    MyBatis-Plus通過插件將數(shù)據(jù)庫表生成Entiry,Mapper.xml,Mapper.class的方式

    今天小編就為大家分享一篇關(guān)于MyBatis-Plus通過插件將數(shù)據(jù)庫表生成Entiry,Mapper.xml,Mapper.class的方式,小編覺得內(nèi)容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧
    2019-02-02
  • java多線程CyclicBarrier的使用案例,讓線程起步走

    java多線程CyclicBarrier的使用案例,讓線程起步走

    這篇文章主要介紹了java多線程CyclicBarrier的使用案例,讓線程起步走!具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2021-02-02
  • SpringBoot2.x中management.security.enabled=false無效的解決

    SpringBoot2.x中management.security.enabled=false無效的解決

    這篇文章主要介紹了SpringBoot2.x中management.security.enabled=false無效的解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-07-07
  • 解決mapstruct在eclipse生成不了mapper的實現(xiàn)類問題

    解決mapstruct在eclipse生成不了mapper的實現(xiàn)類問題

    這篇文章主要介紹了解決mapstruct在eclipse生成不了mapper的實現(xiàn)類問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2023-11-11
  • java實現(xiàn)flappy Bird小游戲

    java實現(xiàn)flappy Bird小游戲

    這篇文章主要為大家詳細(xì)介紹了java實現(xiàn)flappy Bird小游戲,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2018-12-12

最新評論