-1

I have a list of java objects as below

enter image description here

I want to convert it to a list with 'Camera flash faulty' and 'Camera Housing Damaged' only once for the first object, like the one below.

enter image description here

Is there something that can be done with the solution mentioned here ? Remove duplicates from a list of objects based on property in Java 8

Community
  • 1
  • 1
Nevin
  • 769
  • 1
  • 11
  • 26
  • 2
    Collection with unique values suggests that you're looking for a set: `new HashSet<>(list)` – nbrooks Sep 27 '16 at 06:59
  • 2
    Why do you want to *clear* the first attribute ? Does it bother you ? Which problem lies behind that ? It looks like a good candidate for a [XY Problem](http://xyproblem.info/). – Spotted Sep 27 '16 at 07:26
  • 1
    Do you really think, it’s a good idea to modify objects in that way depending on the position in one list? What, if these objects are also contained in a different list, in a different order? What if you remove the first object from the list? – Holger Sep 27 '16 at 10:39
  • This is for the display purpose, the requirement is to display attribute values only once. I am fetching these objects from database, ordering by first column, then second column. so all will be grouped together – Nevin Sep 27 '16 at 23:45

2 Answers2

1

You can add all the properties to a Set (Sets don't allow duplicates), if the value is already in the set, the method add returns false, so you can set to empty the property in the object:

Set<String> values = new HashSet<>();
for (MyObject obj : myList) {
    if (!values.add(obj.getValue())) {
        obj.setValue("");
    }
}

Another alternative is to group all object with the same attribute value, then skip the first element of each group and set the attribute value to empty for all other objects in the group:

    myList.stream()
      .collect(Collectors.groupingBy(MyObject::getValue))
      .forEach((k, v) -> v.stream().skip(1).forEach(o->o.setValue("")));
David SN
  • 3,389
  • 1
  • 17
  • 21
  • David, your second solution is getting me the list with first column in desired manner, but surprisingly its throwing java.sql.SQLSyntaxErrorException: ORA-00942: table or view does not exist when trying to use that list even though there is no database fetch further. I am processing the list after fetch. – Nevin Sep 28 '16 at 00:59
0

I am taking an example of Employee which have some duplicate id's.

Lets say you have a list as

List<Employee> employee

Add them into HashSet, which does not allow duplicates.

HashSet<Object> seen=new HashSet<>();
employee.removeIf(e->!seen.add(e.getID()));
FallAndLearn
  • 4,035
  • 1
  • 18
  • 24
  • FallAndLearn 1,890●1●3●15 I don't want to remove objects with same attribute values, I want to keep them, but make attribute value empty, like in the second list I posted. It doesn't mean those objects are duplicate, it has more attributes which may have different values – Nevin Sep 27 '16 at 07:34