我是Java 8的新手,喜欢比较功能。但是现在我在旧项目中有一些特殊的代码,几乎是不可读的。
程序从另一个数据库导入Object的某些字段到表,如果已经有一个条目,则会得到一个新的版本号。
下一部分是为该客户选择每个条目并查找包含2个版本的条目,然后我对它们进行比较并标记不同的字段,并将旧版本的旧条目放在其后面。
这一切都是通过许多循环,一个comperator和compareTo为40个字段完成的。就像我说的那样,几乎不可读。 Java 8中是否存在类似于此线程的方法 - > https://stackoverflow.com/questions/369512/how-to-compare-objects-by-multiple-fields but with marking of the difference?
答案 0 :(得分:1)
为什么不使用链接中的代码?
Comparator.comparing(Person::getFirstName)
.thenComparing(Person::getLastName)
.thenComparingInt(Person::getAge);
如果您有访问方法:
spinner1.setOnItemSelectedListener(this);
答案 1 :(得分:0)
因此,经过一些搜索,认为Java 8具有良好的比较性,最好的方法是使用一个名为java-object-diff的真正简单的库。
快速测试,基于链接问题中的Person Bean:
public class PersonTest {
@Test
public void test() {
// Old Person
Person person1 = new Person();
person1.setFirstName("Foo");
person1.setLastName("Bar");
person1.setAge("100");
// New Person
Person person2 = new Person();
person2.setFirstName("Foo");
person2.setLastName("bar");
person2.setAge("101");
// Build the DiffNode
DiffNode root = ObjectDifferBuilder.buildDefault().compare(person1, person2);
assertTrue(root.hasChanges());
// Lets compare and change the values
root.visit(new DiffNode.Visitor() {
@Override
public void node(DiffNode node, Visit visit) {
if (node.hasChanges() && !node.hasChildren()) {
node.canonicalSet(person2, node.canonicalGet(person2) + "*");
}
}
});
System.out.println(person1);
System.out.println(person2);
}
}
打印输出:
Person [firstName=Foo, lastName=Bar, age=100]
Person [firstName=Foo, lastName=bar*, age=101*]
通过SuperCSV或Jaxb将其丢弃为CSV文件或XML,客户可以发现更改。或者将person2放入Map并导出刚刚更改的等等。这是我的目标。遗憾的是,项目中没有Java 8和更多的依赖项,但是对于一些不可读的循环来说要好一些:)
- Lord_Pinhead