简体   繁体   English

如何检查一个列表的 object 是否包含另一个列表的任何 object

[英]How to check if an object of one list contains any object of another list

We have two lists one is of type Question and the other of type Tag.我们有两个列表,一个是 Question 类型,另一个是 Tag 类型。

The Question class has those attributes问题 class 具有这些属性

private String id;
private String header;
private String content;
private List<Tag> tags;
private Long timeStamp;

The Question list has all questions in it and the Tag list has all tags in it.问题列表中包含所有问题,标签列表中包含所有标签。 We wanna check if One question contains any tag of the tag list.我们想检查一个问题是否包含标签列表的任何标签。 I want to do this for all questions.我想对所有问题都这样做。

With question.getTags, I get the list of tags.使用 question.getTags,我得到了标签列表。

The Tag class has an attribute called counter.标签 class 有一个称为计数器的属性。

I will give some pseudocode to actually show you what I wanna do我将给出一些伪代码来实际向您展示我想要做什么

List<Tag> allTags = ...
List<Question> allQuestions = ...
Map<Tag,Integer> map = new Hashmap<>();

if(one question contains any tag of allTags) {
     tag.setCounter(counter+1);
     map.put(tag,tag.getCounter);
}

In the end I wanna have a map where the key is the tag and the value the counter of that tag.最后,我想要一个 map,其中键是标签,值是该标签的计数器。

How can I actually do this?我怎么能做到这一点?

EDIT here is my Tag.java编辑这里是我的 Tag.java

@NoArgsConstructor
@Data
@Getter
@AllArgsConstructor
@Setter
@Document(collection = "tag")
public class Tag {
    private String id;
    private String name;
    private Long timeStamp;

public Tag(String name) {
        this.id = UUID.randomUUID().toString();
        this.name = name;
        this.timeStamp = Instant.now().getEpochSecond()*1000;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Tag tag = (Tag) o;
        return Objects.equals(getId(), tag.getId());
    }

    @Override
    public int hashCode() {
        return Objects.hash(getId());
    }
}

I think a counter attribute in the Tag class to count how often a Tag occurs in a list of questions is a design error.我认为Tag class 中的计数器属性用于计算Tagquestions列表中出现的频率是设计错误。 You don't need such a counter there.那里不需要这样的柜台。

A possibly plausible example: Imagine you have a class Student and a class Course .一个可能合理的例子:假设你有一个 class Student和一个 class Course To keep track of how many students are in a course, there is no need for a counter in the Student class.要跟踪课程中有多少学生, Student class 中不需要计数器。 In the same way a class Tag should only contain the attributes of a tag.同样,class Tag应该只包含标签的属性。 That said, you can achieve your goal without the counter with either one of the two following approachs (provided you have java 8 or higher and your Tag class overrides the equals and hashcode methods):也就是说,您可以使用以下两种方法之一在没有计数器的情况下实现您的目标(前提是您有 java 8 或更高版本,并且您的Tag class 覆盖了equalshashcode方法):

Approach 1 using Streams & Collectors.groupingBy方法 1 使用Streams & Collectors.groupingBy

Map<Tag,Long> map = allQuestions.stream()
            .flatMap(q -> q.getTags().stream())
            .filter(allTags::contains)
            .collect(Collectors.groupingBy(Function.identity(),Collectors.counting()));

Approach 2 using List.forEach & Map.compute方法 2 使用List.forEach & Map.compute

Map<Tag, Integer> map2 = new HashMap<>();
    allQuestions.forEach(q -> {
        q.getTags()
                .stream()
                .filter(allTags::contains)
                .forEach(t -> map2.compute(t, (k, v) -> v == null ? 1 : v + 1));
    });

Or using a traditional for-loop and if-else block或者使用传统for-loopif-else

Map<Tag, Integer> map3 = new HashMap<>();

for (Question q : allQuestions) {
    for (Tag t : q.getTags()) {
        if (allTags.contains(t)) {
            if (map3.containsKey(t)) {
                map3.put(t, map3.get(t) + 1);
            } else {
                map3.put(t, 1);
            }
        }
    }
}

I think this will work perfectly我认为这将完美地工作

    int count=0; 
    for(Question q : allQuestions){
     for(Tag t : q.getTags()){
     if(allTags.contains(t)){ 
        count=map.containsKey(t) ? map.get(t)+1 : 0;
        map.put(t,count);
       }
     }
    }

如何检查列表中 Object 的任何 null 字段<object> ?<div id="text_translate"><p> 我有一个 Object 列表传递给如下方法。</p><pre class="lang-java prettyprint-override"> Student s = new Student (name,age,branch, year); // student prototype public void log(List&lt;Student&gt; items) { }</pre><p> 在该方法中,我需要检查每个学生 object 中的任何null值并记录该特定属性,即 null 和相应的学生 ZA8CFDE63131AC4BEB6268CFDE63131AC4BEB8 除了使用之外,还有其他方法可以检查吗?:</p><pre class="lang-java prettyprint-override"> items.stream().anyMatch(item -&gt; item.getAge() == null? System.out.println());</pre><p> 在实际场景中,我的 object 包含 30 多个属性,如果任何一个属性是 null,我想记录 null 属性及其对应的 ZA8CFFDE8911AC</p></div></object> - How to check for any null field of Object in List<Object>?

暂无
暂无

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

相关问题 检查对象列表是否包含Java中的另一个对象 - Check if a list of objects contains another object in Java 检查清单 <Object> 包含一个属性 - Check if a List<Object> contains a property 检查列表是否包含至少一个非null对象 - Check if the list contains at lease one non null object 如何使用lambda或流从包含另一个对象列表的对象列表中迭代和获取对象 - How to iterate and get the object from list of object which contains another list of list of object using lambdas or stream Java 流过一个列表并检查列表是否在列表中包含具有三个给定字段值之一的对象 - Java Stream over a list and check if the list contains at list one object with one of three given field values 检查列表是否至少包含另一个 - 枚举 - Check if list contains at least one of another - enums 如何检查列表中 Object 的任何 null 字段<object> ?<div id="text_translate"><p> 我有一个 Object 列表传递给如下方法。</p><pre class="lang-java prettyprint-override"> Student s = new Student (name,age,branch, year); // student prototype public void log(List&lt;Student&gt; items) { }</pre><p> 在该方法中,我需要检查每个学生 object 中的任何null值并记录该特定属性,即 null 和相应的学生 ZA8CFDE63131AC4BEB6268CFDE63131AC4BEB8 除了使用之外,还有其他方法可以检查吗?:</p><pre class="lang-java prettyprint-override"> items.stream().anyMatch(item -&gt; item.getAge() == null? System.out.println());</pre><p> 在实际场景中,我的 object 包含 30 多个属性,如果任何一个属性是 null,我想记录 null 属性及其对应的 ZA8CFFDE8911AC</p></div></object> - How to check for any null field of Object in List<Object>? 检查对象是否是任何一个类列表的实例(Android) - Check if an object is an instance of any one of a list of classes (Android) 检查List <?>包含的对象类型 - Check which type of object List<?> contains 检查列表是否包含 java 中另一个列表的任何项目 - Check if list contains any item of another list in java
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM