简体   繁体   English

检查一个列表是否包含来自另一个列表的元素

[英]Check if one list contains element from the other

I have two lists with different objects in them.我有两个列表,其中包含不同的对象。

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

I want to check if element from list1 exists in list2, based on specific attribute (Object1 and Object2 have (among others), one mutual attribute (with type Long), named attributeSame).我想根据特定属性(Object1 和 Object2 具有(除其他外)一个相互属性(类型为 Long),名为 attributeSame)检查 list2 中是否存在 list1 中的元素。

right now, I do it like this:现在,我这样做:

boolean found = false;
for(Object1 object1 : list1){
   for(Object2 object2: list2){
       if(object1.getAttributeSame() == object2.getAttributeSame()){
           found = true;
           //also do something
       }
    }
    if(!found){
        //do something
    }
    found = false;
}

But I think there is a better and faster way to do this :) Can someone propose it?但我认为有更好更快的方法来做到这一点:) 有人可以提出建议吗?

Thanks!谢谢!

If you just need to test basic equality, this can be done with the basic JDK without modifying the input lists in the one line如果你只需要测试基本的相等性,这可以用基本的 JDK 来完成,而无需修改一行中的输入列表

!Collections.disjoint(list1, list2);

If you need to test a specific property, that's harder.如果您需要测试特定属性,那就更难了。 I would recommend, by default,我会建议,默认情况下,

list1.stream()
   .map(Object1::getProperty)
   .anyMatch(
     list2.stream()
       .map(Object2::getProperty)
       .collect(toSet())
       ::contains)

...which collects the distinct values in list2 and tests each value in list1 for presence. ...收集list2的不同值并测试list1每个值是否存在。

You can use Apache Commons CollectionUtils :您可以使用Apache Commons CollectionUtils

if(CollectionUtils.containsAny(list1,list2)) {  
    // do whatever you want
} else { 
    // do other thing 
}  

This assumes that you have properly overloaded the equals functionality for your custom objects.这假设您已正确重载自定义对象的 equals 功能。

为了缩短纳伦德拉的逻辑,你可以使用这个:

boolean var = lis1.stream().anyMatch(element -> list2.contains(element));

There is one method of Collection named retainAll but having some side effects for you reference一种名为retainAllCollection方法,但有一些副作用供您参考

Retains only the elements in this list that are contained in the specified collection (optional operation).仅保留此列表中包含在指定集合中的元素(可选操作)。 In other words, removes from this list all of its elements that are not contained in the specified collection.换句话说,从该列表中删除所有未包含在指定集合中的元素。

true if this list changed as a result of the call如果此列表因调用而更改,则为 true

Its like就像是

boolean b = list1.retainAll(list2);

Loius answer is correct, I just want to add an example: Loius 的回答是正确的,我只想添加一个示例:

listOne.add("A");
listOne.add("B");
listOne.add("C");

listTwo.add("D");
listTwo.add("E");
listTwo.add("F");      

boolean noElementsInCommon = Collections.disjoint(listOne, listTwo); // true

to make it faster, you can add a break;为了让它更快,你可以添加一个休息时间; that way the loop will stop if found is set to true:这样,如果 found 设置为 true,则循环将停止:

boolean found = false;
for(Object1 object1 : list1){
   for(Object2 object2: list2){
       if(object1.getAttributeSame() == object2.getAttributeSame()){
           found = true;
           //also do something  
           break;
       }
    }
    if(!found){
        //do something
    }
    found = false;
}

If you would have maps in stead of lists with as keys the attributeSame, you could check faster for a value in one map if there is a corresponding value in the second map or not.如果您将使用地图而不是将属性作为键的列表,您可以更快地检查一张地图中的值是否在第二张地图中存在相应的值。

According to the JavaDoc for the .contains(Object obj) :根据.contains(Object obj)的 JavaDoc:

Returns true if this list contains the specified element.如果此列表包含指定的元素,则返回 true。 More formally, returns true if and only if this list contains at least one element e such that (o==null ? e==null : o.equals(e)).更正式地说,当且仅当此列表包含至少一个元素 e 使得 (o==null ? e==null : o.equals(e)) 时才返回 true。

So if you override your .equals() method for your given object, you should be able to do: if(list1.contains(object2))...因此,如果您覆盖给定对象的.equals()方法,您应该能够执行以下操作: if(list1.contains(object2))...

If the elements will be unique (ie. have different attributes) you could override the .equals() and .hashcode() and store everything inHashSets .如果元素是唯一的(即具有不同的属性),您可以覆盖.equals().hashcode()并将所有内容存储在HashSets This will allow you to check if one contains another element in constant time.这将允许您在恒定时间内检查一个元素是否包含另一个元素。

faster way will require additional space .更快的方式将需要额外的空间。

For example:例如:

  1. put all items in one list into a HashSet ( you have to implement the hash function by yourself to use object.getAttributeSame() )将一个列表中的所有项目放入一个 HashSet (您必须自己实现哈希函数才能使用 object.getAttributeSame() )

  2. Go through the other list and check if any item is in the HashSet.浏览另一个列表并检查 HashSet 中是否有任何项目。

In this way each object is visited at most once.这样每个对象最多被访问一次。 and HashSet is fast enough to check or insert any object in O(1). HashSet 足够快,可以在 O(1) 中检查或插入任何对象。

Can you define the type of data you hold ?你能定义你持有的数据类型吗? is it big data ?是大数据吗? is it sorted ?排序了吗? I think that you need to consider different efficiency approaches depending on the data.我认为您需要根据数据考虑不同的效率方法。

For example, if your data is big and unsorted you could try and iterate the two lists together by index and store each list attribute in another list helper.例如,如果您的数据很大且未排序,您可以尝试通过索引将两个列表迭代在一起,并将每个列表属性存储在另一个列表助手中。 then you could cross check by the current attributes in the helper lists.然后您可以通过助手列表中的当前属性进行交叉检查。

good luck祝你好运

edited : and I wouldn't recommend overloading equals.编辑:我不建议重载等于。 its dangerous and probably against your object oop meaning.它是危险的,可能违反您的对象 oop 含义。

org.springframework.util.CollectionUtils org.springframework.util.CollectionUtils

boolean containsAny(java.util.Collection<?> source, java.util.Collection<?> candidates)

Return true if any element in 'candidates' is contained in 'source'; otherwise returns false

使用java 8 ,我们可以像下面那样检查一个列表是否包含其他列表的任何元素

boolean var = lis1.stream().filter(element -> list2.contains(element)).findFirst().isPresent();

I have two lists with different objects in them.我有两个带有不同对象的列表。

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

I want to check if element from list1 exists in list2, based on specific attribute (Object1 and Object2 have (among others), one mutual attribute (with type Long), named attributeSame).我想检查list1中的元素是否存在于list2中,它基于特定的属性(Object1和Object2具有(以及其他),一个共有属性(类型为Long),名为attributeSame)。

right now, I do it like this:现在,我这样做是这样的:

boolean found = false;
for(Object1 object1 : list1){
   for(Object2 object2: list2){
       if(object1.getAttributeSame() == object2.getAttributeSame()){
           found = true;
           //also do something
       }
    }
    if(!found){
        //do something
    }
    found = false;
}

But I think there is a better and faster way to do this :) Can someone propose it?但是我认为有一种更好,更快的方法可以做到这一点:)有人可以提出吗?

Thanks!谢谢!

检查一个列表<string>包含列表中的所有元素<object>使用 stream<div id="text_translate"><p> 我有 2 个列表:</p><pre> List<String> authorizedList; // ["11","22","33"] List<MySerial> serials; // [Myserial1,Myserial2,Myserial3] =></pre><p> MySerial 是 object,有 2 个参数,Myserial(String serial, String name)</p><p> 我想使用 stream 检查是否所有来自连续剧的连续剧都在 authorizedList 中,但我是新手。</p><pre> if (.serials.stream():map(MySerial:.getSerial):anyMatch(authorizedList:;equals)) { throw new UnauthorizedException(); }</pre><p> 但它总是抛出异常。</p></div></object></string> - Check if a List<String> contains all element from a List<Object> using stream

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 检查一个列表是否包含相同的元素,然后在另一个列表上获取一些值 - Check if a list contains the same element then get some values on the other list 检查字符串是否包含列表中的元素 - Check if a String contains an element from a List 如何检查集合中是否包含Scala中其他集合的任何元素? - How to check if collection contains any element from other collection in Scala? 检查列表列表是否包含列表中的任何子列表匹配元素 - Check If List of Lists Contains Any Sub List Matching Element from List 如何使用AssertJ检查某些List是否仅包含一个特定元素或为空 - How to check if some List contains only one particular element OR is empty using AssertJ 检查List是一种类型还是其他类型 - Check if List is of one type or other 检查一个列表<string>包含列表中的所有元素<object>使用 stream<div id="text_translate"><p> 我有 2 个列表:</p><pre> List<String> authorizedList; // ["11","22","33"] List<MySerial> serials; // [Myserial1,Myserial2,Myserial3] =></pre><p> MySerial 是 object,有 2 个参数,Myserial(String serial, String name)</p><p> 我想使用 stream 检查是否所有来自连续剧的连续剧都在 authorizedList 中,但我是新手。</p><pre> if (.serials.stream():map(MySerial:.getSerial):anyMatch(authorizedList:;equals)) { throw new UnauthorizedException(); }</pre><p> 但它总是抛出异常。</p></div></object></string> - Check if a List<String> contains all element from a List<Object> using stream 检查列表是否至少包含另一个 - 枚举 - Check if list contains at least one of another - enums 一个衬垫,用于检查元素是否在列表中 - One liner to check if element is in the list 如何检查字符串列表中的特定单词是否包含在字符串中,但不应该在任何其他单词之间? - How to check if a particular word from a string list contains in a string, but it should not be between any other words?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM