集合类型转换:array,map,list,set:枚举

本文介绍了如何在Java中将数组转换为列表List,以及如何将列表转换为数组。同时,文章详细展示了如何利用Stream API将List转换为Map,包括不同情况下的Key冲突处理策略。通过示例代码,演示了如何取列表中特定字段作为Map的Key和Value,以及使用特定Map实现(如LinkedHashMap)进行转换。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

数组快速传创建:

int[] ar1 = IntStream.rangeClosed(1,5).toArray();

int [] ar2 = IntStream.iterate(1,x->2*x).limit(10).toArray();

数组转为列表list

  1. 尽量使用 Arrays.asList 转化数组为列表
String[] strings = {"a","b","c"};

 List list = Arrays.asList(strings);
  1. 列表转为数组:
集合转化为 Object 数组时,尽量使用 toArray()方法
转化 Object 数组时,没有必要使用 toArray[new Object[0]],可以直接使用 toArray()。
避免了类型的判断,也避免了空数组的申请,所以效率会更高。
String[] strings1 = (String[]) list.toArray();

Integer[] objects2 = list1.toArray(new Integer[0]);
  1. 枚举类型直接转为数组工具:
   TestEnum[] values = TestEnum.values();
	for (TestEnum value:
             values) {

第一种: 取list中某2个字段作为Map的K,V
第二种:将id和实体Bean做为K,V
第三种: key存在重复记录时处理
第四种: 使用某个具体的Map类来保存,如保存时使用LinkedHashMap’, '第一种: 取list中某2个字段作为Map的K,V

public Map<Long, String> getIdNameMap(List<User> users) {
    return accounts.stream().collect(Collectors.toMap(User::getId, User::getUserName));
}
//第二种:将id和实体Bean做为K,V account -> account是一个返回本身的lambda表达式,后面的使用Function接口中的一个默认方法代替,使整个方法更简洁优雅。
public Map<Long, Account> getIdAccountMap(List<Account> accounts) {
    return accounts.stream().collect(Collectors.toMap(Account::getId, account -> account));
}
public Map<Long, Account> getIdAccountMap(List<Account> accounts) {
    return accounts.stream().collect(Collectors.toMap(Account::getId, Function.identity()));
}
//第三种: key存在重复记录时处理,如果使用第一种方法会出错,所以这里只是简单的使用后者覆盖前者来解决key重复问题
public Map<String, Account> getNameAccountMap(List<Account> accounts) {
    return accounts.stream().collect(Collectors.toMap(Account::getUsername, Function.identity(), (key1, key2) -> key2));
}
//第四种: 使用某个具体的Map类来保存,如保存时使用LinkedHashMap
public Map<String, Account> getNameAccountMap(List<Account> accounts) {
    return accounts.stream().collect(Collectors.toMap(Account::getUsername, Function.identity(), (key1, key2) -> key2, LinkedHashMap::new));
}

Stream将List转换为Map,使用Collectors.toMap方法进行转换。

1、指定key-value,value是对象中的某个属性值。

Map<Integer,String> userMap1 = userList.stream().collect(Collectors.toMap(User::getId,User::getName));

2、指定key-value,value是对象本身,User->User 是一个返回本身的lambda表达式

Map<Integer,User> userMap2 = userList.stream().collect(Collectors.toMap(User::getId,User->User));

3、指定key-value,value是对象本身,Function.identity()是简洁写法,也是返回对象本身

Map<Integer,User> userMap3 = userList.stream().collect(Collectors.toMap(User::getId, Function.identity()));

4、指定key-value,value是对象本身,Function.identity()是简洁写法,也是返回对象本身,key 冲突的解决办法,这里选择第二个key覆盖第一个key。

Map<Integer,User> userMap4 = userList.stream().collect(Collectors.toMap(User::getId, Function.identity(),(key1,key2)->key2));

5、拼接key
Map<String, Parts> partsMap = synList.stream().collect(Collectors.toMap(k -> k.getOe()+k.getOeId()+k.getPartGroupId()+k.getStdPartId()+k.getBrandCode(), part -> part));
 

HashMap<Integer, User> users = new HashMap<>();

        users.put(1, new User("张三", 25));
        users.put(3, new User("李四", 22));
        users.put(2, new User("王五", 28));
        System.out.println(users);

        List<Map.Entry<Integer, User>> list = new ArrayList<>(users.entrySet());
//{1=User(name=张三, age=25), 2=User(name=王五, age=28), 3=User(name=李四, age=22)}
//[1=User(name=张三, age=25), 2=User(name=王五, age=28), 3=User(name=李四, age=22)]
        System.out.println(list);


        List<Map.Entry<Integer, User>> list1 = list.stream().sorted(Map.Entry.comparingByValue(Comparator.
                        comparing(User::getAge).reversed())).collect(Collectors.toList());

         list.stream().sorted(Comparator.comparing(Map.Entry::getValue, (s1, s2) -> s2.getAge().compareTo(s2.getAge())))
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

        System.out.println("list1:"+list1);


        LinkedHashMap<Integer, User> linkedHashMap2 = new LinkedHashMap<Integer, User>();
        //将 List 中的数据存储在 LinkedHashMap 中
        for (Map.Entry<Integer, User> entry : list1) {
            linkedHashMap2.put(entry.getKey(), entry.getValue());
        }

        System.out.println("LinkedHashMap:" + linkedHashMap2);

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值