-1

I got a list of custom objects in it. Every of these objects has a unique ID, but some of them got same names. I want to remove the duplicated objects by name (string value). Found this example in a similar question, but it compares the IDs, not the names.

List<Relation> unique = possibleRels.stream().collect(collectingAndThen(toCollection(() -> new TreeSet<>(comparingInt(Relation::getId))), t -> new ArrayList<>(t)));

Is there a method to delete duplicates from list, compared by a string value?

Lazar Zoltan
  • 135
  • 3
  • 14
  • This did the trick: possibleRelations.stream().collect(Collectors.groupingBy(p -> p.getName())).values().forEach(t -> unique.add(t.get(0))); – Lazar Zoltan Apr 15 '20 at 14:37

3 Answers3

0

Maybe you can use a hashset to remove all values, then put them back again. I can't see what you tried, so I don't really understand what you want.

TheXDShrimp
  • 116
  • 13
0

You can make the object comparable according to id or name and after that you should check if the lists contains the element. Contains return false if the list contains element with the same id or the same name.

Sassy
  • 1
  • 5
0

To remove the duplicated objects by name (string value), as opposed to building a new list without them, use a stateful removeIf().

Set<String> names = new HashSet<>();
possibleRels.removeIf(e -> ! names.add(e.getName()));
Andreas
  • 154,647
  • 11
  • 152
  • 247