0

working with a given class like this

class MyClass{
private String name;
MyClass(String name){this.name=name;}
public String getName(){return this.name;}
}

with a collection like this

List<MyClass>cl = Arrays.asList(
            new MyClass("Mike"),
            new MyClass("Luke"),
            new MyClass("John"),
            new MyClass("Mike"),
            new MyClass("Luke")
            );

i am able to have a String list of unique names

List<String>uniqueNames = cl.stream().map(a->a.getName()).distinct()
.collect(Collectors.toList());

what i want is MyClass list instead of a String list but i don't get how to return MyClass instead of the String from .getName() inside the stream

edit: that "duplicate" just explains the distinct function, i put .distinct() just as an example, i may want all the classes with names that begins with "M" for example. I want to know the best way to return a class object when i check the predicate with .map() or something equivalent instead of using a filter.

Tagir Valeev
  • 97,161
  • 19
  • 222
  • 334
T4l0n
  • 595
  • 1
  • 8
  • 25
  • I suggest you add `equals(Object)` and `hashCode()` to MyClass then you will be able to add them to a set which is a more natural collection if you have distinct elements. – Peter Lawrey Dec 03 '15 at 18:52
  • Nevertheless it's a duplicate (or you badly formulated your question). Will `cl.stream().map(a->a.getName()).distinct().map(MyClass::new).collect(toList())` satisfy you? – Tagir Valeev Dec 06 '15 at 11:35

0 Answers0