Requirement -
I have a list of objects as given below -
[
TestObj{levelCode='123', operId='ABC', hrchyInd='S'},
TestObj{levelCode='456', operId='DEF', hrchyInd='S'},
TestObj{levelCode='123', operId='ABC', hrchyInd='M'}
]
My desired output is -
[
TestObj{levelCode='123', operId='ABC', hrchyInd='B'},
TestObj{levelCode='456', operId='DEF', hrchyInd='S'},
]
If two TestObj
in the list are having the same levelCode && OperId
but different hrchyInd
then we should include only one TestObj
out of the two in the output list and modify the hrchyInd
as B
.
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.ToString;
@Data
@AllArgsConstructor
@ToString
@Builder
public class TestObj {
private String levelCode;
private String operId;
private String hrchyInd;
}
Can anyone please help me to solve this problem in an optimal way.
CodePudding user response:
I cannot speak to Lombok, as I’ve never used it. Otherwise, here is what I would do.
Override equals
and hashCode
to consider the two member fields, levelCode
and operId
, but not hrchyInd
.
When adding to your list or set, first test if the collection contains said item. If not, proceed with adding. If found, change the hrchyInd
field value of additional item to B
, and replace existing item.
CodePudding user response:
Few suggestions to accomplish this:
- Since you are dealing with custom objects and not literals, first thing is override equals() method of the TestObj class. Make sure that you check the appropriate equality.
- Add all such objects to a collection (ArrayList for example)
- From here either you can create a Set (HashSet) from the list or use Stream distinct method to filter out the duplicates.