0

I have a pojo class

public class SomeClass {
    
    private int id;
    private String name;
    public SomeClass(int id, String name) {
        super();
        this.id = id;
        this.name = name;
    }
}

Also I have list

SomeClass s1 = new SomeClass(1, "abc");
SomeClass s2 = new SomeClass(2, "xyz");
SomeClass s3 = new SomeClass(5, "abc");
SomeClass s4 = new SomeClass(6, "rst");
SomeClass s5 = new SomeClass(2, "xyz");
SomeClass s6 = new SomeClass(3,"xyz");
SomeClass s7 = new SomeClass(9,"der");

        
List<SomeClass> list = Arrays.asList(s1,s2,s3,s4,s5,s6,s7);

I want to filter out objects from list having same name property . For example s1 and s3 have same name property. Also s2, s5, s6 have same property

The output that is the filtered list should have s1 , s3 , s2 , s5 , s6 as elements. How do I do this using java streams API ?

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
  • Does this answer your question? [Java 8 Distinct by property](https://stackoverflow.com/questions/23699371/java-8-distinct-by-property) – MC Emperor Oct 12 '21 at 16:07
  • 1
    Which element should be chosen if 2 have the same `name`? – Sotirios Delimanolis Oct 12 '21 at 16:09
  • What have you tried? This site is not a code-writing service. We can help you with *specific* questions about *your* code, ideally accompanied by an [MCVE](https://stackoverflow.com/help/mcve). Not having written any code is not considered a “problem” we should solve. – Bohemian Oct 12 '21 at 16:12
  • Thanks for letting me know this ain't a code writing service. Nobody has asked you to come and vomit here and I am not obliged to show you what I have tried and what not as you have not even answered. Please don't make this world negative fella @bohemian – Santosh Kamat Oct 14 '21 at 01:38

2 Answers2

1

I would groupBy name and then filter lists with only one element.

Map<String, List< SomeClass >> someClassByName =
    list.stream().collect(Collectors.groupingBy(sc -> sc.name));

List<SomeClass> filteredList = someClassByName.values().stream()
    .filter(listForName -> listForName.size() > 1)
    .flatMap(List::stream)
    .collect(Collectors.toList());

Thomas Martin
  • 678
  • 8
  • 19
-1

try this

 public static void main(String args[]) {
    List<String> distinct = list.stream().distinct().collect(Collectors.toList());
    
    for(String str : distinct) {
                System.out.println(str);
    }

    }