0

Topic is an object made up of:

String Name
Int Id

e.g.

topic1:
Name: Topic1
Id: 1

topic2:
Name: Topic1
Id: 2

I have a list of {topic1, topic2}

I want a list of topics with unique names. So my ideal output would be a list containing just {topic1}.

.distinct() doesn't work because the Ids are different, so the objects are different.

How do I get this in Java?

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
  • If two objects have the same name, which object do you want to keep? What if your list is `[topic2, topic1]`? – peer Sep 15 '22 at 20:41
  • 1
    Fundamentally, the system can't "just know" what operation you want to preform on a list like this, so it only provides primitives and you have to be able to supply the rest. Take a look at [method references](https://docs.oracle.com/javase/tutorial/java/javaOO/methodreferences.html) and the way they are used to parameterize various list operators. – markspace Sep 15 '22 at 20:44
  • That said, I'd agree that not having some sort of "removeAll( predicate )" for a list might be a bit of an oversight. – markspace Sep 15 '22 at 20:46
  • 1
    @markspace You mean `removeIf()`? – shmosel Sep 15 '22 at 20:49
  • I said "for a list" and meant the `List` interface, so no not really. I suppose I should have been more clear. But "removeIf" on List would be a lot handier than having it only ArrayList (which is what I assume you mean). – markspace Sep 15 '22 at 20:51
  • 2
    @markspace It's on `Collection`. – shmosel Sep 15 '22 at 20:53
  • OK I stand corrected then. – markspace Sep 15 '22 at 20:55
  • FYI: [`Collection#removeIf( Predicate )`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/Collection.html#removeIf(java.util.function.Predicate)) in Java 8+. – Basil Bourque Sep 15 '22 at 22:49

0 Answers0