java中list与map的互转与去重

先创建一个Person实体

@Data

public class Person{

     private String name;

     private Integer age;

}

List<Person> personList = new ArrayList<>();

1、将List转换为Map,以name作为key,age作为value。同时指定当键值重复时选取新的键值对。

Map map = personList.stream().collect(Collectors.toMap(Person::getName, Person::getAge,(oldValue, newValue) -> newValue));

2、将List转换为Map,以name作为key,本身作为value。同时指定当键值重复时选取新的键值对。

Map map = personList.stream().collect(Collectors.toMap(Person::getName, s->s,(oldValue, newValue) -> newValue));

3、将List转换为Map,以两个字段相加作为key,本身作为value。同时指定当键值重复时选取旧的键值对。

Map map = personList.stream().collect(Collectors.toMap((s) -> s.getName() + ";" + s.getAge(), (s) -> s, (oldValue, newValue) -> oldValue));

4、List根据属性name,age去重

List<Person> distinctList = personList.stream().collect(
   Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(
       Comparator.comparing(MyClass::getName)
           .thenComparing(MyClass::getAge))   //按单个属性去重时,去掉thenComparing即可
   )), ArrayList::new));

5、输出list中年龄等于5的第一个匹配到的对象,没有时返回null

Person person = personList.stream().filter(s -> s.getAge()==5).findFirst().orElse(null);   //filter有多个属性时,用&&拼接

6、输出list中名字等于张三的第一个匹配到的对象,没有时返回null

Person person = personList.stream().filter(s -> s.getName().equals("张三")).findFirst().orElse(null);

7、收集list中名字等于张三的所有对象,并根据age去重

List<Person> person = personList.stream().filter(s -> s.getName().equals("张三")).collect(
        Collectors.collectingAndThen(
                Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(s -> s.getAge()))), ArrayList::new));

8、将list中的age组成新的list

List<Integer> list =personList.stream().map(Person::getAge).collect(Collectors.toList());

9、 将map中的value转为List

List distinct = new ArrayList<>(map.values());

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值