java - 检查一个列表是否包含相同的元素,然后获取另一个列表上的一些值

标签 java list

我有两个列表,其中包含相同的对象。

List<Object1> list1;
List<Object1> list2;

for (Object1 objectItem : list1.getList()) {
    // I want to check if objectItem exists in list2 without using another for loop and then compare their other values
    // Something like list2.getList().contains(objectItem).getThisValueMethod();
}

这可能吗?

最佳答案

考虑这个示例(注释中的说明):

// Suppose you have two lists of Objects (Strings in this case)
List<String> list1 = new ArrayList<String>();
List<String> list2 = new ArrayList<String>();

//fill them with some example data
list1.add("1"); list1.add("2"); list1.add("3"); 
list2.add("0"); list2.add("1"); list2.add("2");

// Now you can use ONE for-loop as you asked to check equality
for (String s : list1) {
    if(list2.contains(s)){ // use contains() method which returns true if the Object found
    // indexOf(Object) this method return the index of the given Object in the list
    // get(int index) this return the OBJECT from the list
    // and because Java works by passing reference of object -> you can directly invoke any method
    // that is originally in that Object Class

       list2.get(list2.indexOf(s)); // you can invoke a method on it 
    // because in this case it's a String I can invoke any method from Class String
    // on the the above-object, for example
       list2.get(list2.indexOf(s)).trim(); // this method to remove leading spaces.. and so on

       System.out.println(list2.get(list2.indexOf(s))); // for testing
    }
}

关于java - 检查一个列表是否包含相同的元素,然后获取另一个列表上的一些值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44146943/

相关文章:

java - 错误 : Wrapper cannot find servlet class VendorRegistration or a class it depends on

c# - 如何使用 LINQ 计算列表中列表中列表的元素?

python - xls Python 的元组列表

list - Prolog 反转列表 - 快速方法

python - 在python中的自身列表上迭代丢番图方程

java - spring RestTemplate POST 请求的问题

java - 在新方法中使用 boolean 结果时出错 - 需要字符串,但找到 boolean 值

java - 使用 JSON 文件初始化静态类

Java Jigsaw JUnit 测试 - JUnit 不在模块中

python - 如何根据给定的开始日期和结束日期过滤包含日期的列表?