java——如何比较两组对象不使用 Comparator 和 Streams 覆盖 equals/hashCode
发布时间:2022-09-09 09:47:46 365
相关标签: # 移动端
我有两个Set
它是这样的:
Set s1 = createBooks();
Set s2 = createBooks(); // or any set of values
这种方法:
private Set createBooks() {
List name = Arrays.asList("book 1", "book 2", "book 3");
List type = Arrays.asList(BookType.TYPEONE, BookType.TYPETWO);
Set listOfBooks = new HashSet<>();
for(int i=0; i<2; i++) {
Book book = new Book();
book.setName(name.get(i));
book.setType(type.get(i));
listOfBooks.add(books);
}
return listOfBooks;
}
还有这门课:
Class Book {
private String name;
private BookType type;
//here is getter and setter ...
}
我确实做到了Comparator
,但我不确定它是否正常工作:
Comparator comparingBooks = (o1, o2) -> {
if (o1.getName().compareTo(o2.getName()) == 0) {
return o1.getType().compareTo(o2.getType());
}
return o1.getName().compareTo(o2.getName());
};
//I did try this implementation but am not sure it's working as well:
//Comparator comparingBooks = Comparator.comparing((Book b)->b.getNName())
.thenComparing(b->b.getType());
当预期结果为true
:
s1 = (new Book("book 1", BookType.ONE), new Book("book 2", BookType.TWO));
s2 = (new Book("book 1", BookType.ONE), new Book("book 2", BookType.TWO));
当预期结果为false
:
s1 = (new Book("book 1", BookType.ONE), new Book("book 2", BookType.TWO));
s2 = (new Book("book 1", BookType.ONE), new Book("book 2", BookType.ONE));
我需要将这些集合与以下内容进行比较:
// this flag should validate any difference of Name
// and Type by returning true,
// if both Sets have exactly the same objects,
// it should return false.
boolean compareBooks = s1.stream().anyMatch(a -> s2.stream().anyMatch(b -> comparingBooks.compare(a, b) != 0));
我也尝试过,但没有成功,总是返回相同的值:
boolean compareBooks = SetUtils.isEqualSet(s1, s2);
我没有equals和hashcode实现,无法实现。
java 8和comparator还有其他方法来检查和比较这些集合吗?
特别声明:以上内容(图片及文字)均为互联网收集或者用户上传发布,本站仅提供信息存储服务!如有侵权或有涉及法律问题请联系我们。
举报