比较不同类型的列表 [英] Comparing lists of different types

查看:74
本文介绍了比较不同类型的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下两个列表

List<MyObject1> list1
List<Long> list2

list2基本上是MyObject1的ID的列表,它是对象中的一个属性

The list2 is basically the list of Id's of MyObject1 which is a property in the object

Public Class MyObject1 implements Serializable{

    private Long myObjId;
     .....
      .....
      //other elements go here

   public Long getMyObjId() {
    return myObjId;
    }

    public void setMyObjId(Long myObjId) {
    this.myObjId = myObjId;
}

我想比较两个列表,以检查list1中的所有对象是否都包含在list2中

I want to compare the two lists to check if all the objects in list1 are contained in list2

一种方法是遍历list1,从中创建一个新的ID列表,然后在其上使用containsAll方法.

One way is to iterate over the list1, create a new list of Id's out of it and then use the containsAll method on it.

有没有更简单的方法来达到相同的结果?

Is there a simpler way to achieve the same result?

推荐答案

在Java 8中,您可以编写您所描述的内容:一种方法是遍历list1,从中创建一个新的ID列表,然后使用containsAll方法就可以了."在一行中为:

In Java 8 you can write what you described: "One way is to iterate over the list1, create a new list of Id's out of it and then use the containsAll method on it." in one line as:

list1.stream().map(a -> a.getMyObjId()).collect(Collectors.toList()).containsAll(list2);

map 通过调用a.getMyObjectId将每个MyObeject转换为ID,然后 collect 创建一个列表结果.

map converts a each MyObeject to an id by calling a.getMyObjectId and collect creates a list as a result.

这篇关于比较不同类型的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆