0

I want to group Person objects base on gender with Collectors.toMap() function as describe below, but this does not work as I expected.

class Person{
   private Integer id;
   private String gender;
   private String name;
   public String getGender(){
       return gender;
   }
   public Person(Integer id, String gender, String name){
       this.id=id;
       this.gender=gender;
       this.name=name;    
   }
}


public static void main(String[]args){
   List<Person> persons=new ArrayList<>();
   persons.add(new Person(1,"Man","John"));
   persons.add(new Person(2,"Man","Steve"));
   persons.add(new Person(3,"Women","Linda"));
   persons.add(new Person(4,"Man","Bill"));
   persons.add(new Person(5,"Women","Siti"));
   persons.add(new Person(6,"Man","Buzzer"));

   Map<String,List<Person>> filtered=persons
            .stream()
            .collect(Collectors.toMap(Person:getGender:Function.identity()));

}

Error hint

incompatible types: inference variable U has incompatible bounds equality constraints: List lower bounds: Person,T#2,T#1 where U,T#1,K,T#2 are type-variables: U extends Object declared in method <T#1,K,U>toMap(Function<? super T#1,? > > extends K>,Function<? super T#1,? extends U>) T#1 extends Object declared in method <T#1,K,U>toMap(Function<? super T#1,? > extends K>,Function<? super T#1,? extends U>) K extends Object declared in method <T#1,K,U>toMap(Function<? super T#1,? > extends K>,Function<? super T#1,? extends U>) T#2 extends Object declared in method <T#2>identity()

type of <R,A>collect(Collector<? super T,A,R>) is erroneous where R,A,T are type-variables: R extends Object declared in method <R,A>collect(Collector<? super T,A,R>) A extends Object declared in method <R,A>collect(Collector<? super T,A,R>)

Can someone explain this error?

2 Answers 2

1

Try this:

final var filtered = persons.stream().collect(Collectors.groupingBy(Person::getGender));
Sign up to request clarification or add additional context in comments.

1 Comment

this work but i wonder when add forEach((gender,p)->{ System.out.println(gender};); this work
0

Collectors.toMap() isn't that good for what you want to do. Instead try out Collectors.groupingBy().

Map<String,List<Person>> filtered = persons.stream().collect(Collectors.groupingBy(Person::getGender));

2 Comments

@magicom, so Collectors.groupingBy best what for?
Well groupingBy is as the name suggest best for grouping stuff. So you have one key and multiple values. toMap is much simpler and just accepts two functions to create your key and value.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.