[英]How to check if an object of one list contains any object of another list
我們有兩個列表,一個是 Question 類型,另一個是 Tag 類型。
問題 class 具有這些屬性
private String id;
private String header;
private String content;
private List<Tag> tags;
private Long timeStamp;
問題列表中包含所有問題,標簽列表中包含所有標簽。 我們想檢查一個問題是否包含標簽列表的任何標簽。 我想對所有問題都這樣做。
使用 question.getTags,我得到了標簽列表。
標簽 class 有一個稱為計數器的屬性。
我將給出一些偽代碼來實際向您展示我想要做什么
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);
}
最后,我想要一個 map,其中鍵是標簽,值是該標簽的計數器。
我怎么能做到這一點?
編輯這里是我的 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());
}
}
我認為Tag
class 中的計數器屬性用於計算Tag
在questions
列表中出現的頻率是設計錯誤。 那里不需要這樣的櫃台。
一個可能合理的例子:假設你有一個 class Student
和一個 class Course
。 要跟蹤課程中有多少學生, Student
class 中不需要計數器。 同樣,class Tag
應該只包含標簽的屬性。 也就是說,您可以使用以下兩種方法之一在沒有計數器的情況下實現您的目標(前提是您有 java 8 或更高版本,並且您的Tag
class 覆蓋了equals
和hashcode
方法):
方法 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()));
方法 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));
});
或者使用傳統for-loop
和if-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);
}
}
}
}
我認為這將完美地工作
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);
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.