[JAVA] Process to check if "some fields are duplicated" from the Bean List

Java after a long time. When I was asked, I couldn't think of it.

Proposal 1: I'll do my best with a dedicated Comparator and TreeSet

The first thing I came up with was how to create a Comparator for any field and eliminate duplicates with TreeSet (I don't know what duplicates are).

https://wandbox.org/permlink/Jy1QULC9vOUBSmIp

When the number of fields increases, it feels like writing with a ternary operator. However, it is necessary to define the Comparator for each bean. .. And there is no doubt that it will be killed by the Null Pointer Exception police. So I considered it.

https://wandbox.org/permlink/PTMp9eDR7M5YeHS1

... This method seems to be buggy and I'm not confident. In fact, I stepped on the NullPointerException many times while writing.

Proposal 2: Write only getter and leave the comparison to List

After thinking about what this annoyance was, I came up with the idea that it was necessary to select the fields to be compared by equals and to compare each. So

--Just write a getter to get the fields to be compared --When comparing, make a List of the obtained values and rely on the equals that the List has.

I thought that if you do this, the troublesomeness of comparison will be reduced. How about that.

https://wandbox.org/permlink/TDiFmIy3GfL2EmB9

On the other hand, I don't want to write each bean one by one, so I want the bean to have a good method.

Proposal 3: I want to do it with Annotation Processing

Isn't it possible to add interfaces and methods by doing something like lombok? I thought. However, I gave up because it seemed necessary to do some research and tamper with the existing files while looking at the AST.

Is there the best way?

~~ I'm sorry I wrote the method name in snake case. ~~

Recommended Posts

Process to check if "some fields are duplicated" from the Bean List
How to change the process depending on the list pressed when there are multiple ListViews
How to check if the characters entered in the Swift Text Field are email addresses
Check if Ethereum transactions are not included in the block
If you want to change the Java development environment from Eclipse
Determine if the strings to be compared are the same in Java