0

I have a List of objects and I want to remove the duplicates based on criteria: compare the descr value, if at least one row has Invalid as descr's value, use that object and remove the rest of the objects with the same row value.

class Sample {
  public String row;
  public String descr;
}

Sample input data:

[{"01", "Invalid"}, {"01", "One more"}, {"02", "Invalid"}, {"03", "another test"}]

Result should be:

[{"01", "Invalid"}, {"02", "Invalid"}, {"03", "another test"}]
x80486
  • 6,627
  • 5
  • 52
  • 111
user1015388
  • 1,283
  • 4
  • 25
  • 45
  • What if there are no "Invalid"s in a row#, do you keep them all? Also do you have to use streams? Also is your example code even written in Java? – Peter Hull Jul 01 '19 at 19:54
  • yes, keep the rest of them . Good to use streams if possible. Yes I am using Java. – user1015388 Jul 01 '19 at 19:56
  • 1
    I disagree with the claim that this is a duplicate of "Java 8 Distinct by Property" – Peter Hull Jul 02 '19 at 05:47
  • Sorry, but this description makes no sense at all: “if at least one `row` has `Invalid` as `descr`'s value”. – Holger Jul 02 '19 at 11:13

1 Answers1

4

Set

A Set in Java is a collection of objects without duplicates.

The idea would be :

  • Storing in a Set the row values of the objects where desc equals to "Invalid".
  • Applying removeIf() on the initial list to remove elements that have row values contained in the Set but with descr not equals to "Invalid".

Such as :

List<Foo> foos = ...;

Set<String> invalidRows = 
foos.stream()
    .filter(f->f.getDescr().equals("Invalid"))
    .map(Foo::getRow)
    .collect(toSet());

foos.removeIf(f-> invalidRows.contains(f.getRow()) && !f.getDescr().equals("Invalid"))
azro
  • 53,056
  • 7
  • 34
  • 70
davidxxx
  • 125,838
  • 23
  • 214
  • 215