gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 02:31:46 24 4
gpt4 key购买 nike

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

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com