Print all the names of student in alphabetical order by gender in java 8 using Stream API

This question is some tricky, you have to create enum and student class then sorted the predefined condition in question.

Enum of Gender
public enum Gender {
 MALE,FEMALE;

}


Person Class with getter , setter and override to string method.
public class Person {
 
 public Gender getGender() {
  return gender;
 }
 public void setGender(Gender gender) {
  this.gender = gender;
 }
 public Person(String fn, String ln, Gender g){
  
  this.fName=fn;
  this.lName=ln;
  this.gender=g;
  
 }
 public String getfName() {
  return fName;
 }
 public void setfName(String fName) {
  this.fName = fName;
 }
 public String getlName() {
  return lName;
 }
 public void setlName(String lName) {
  this.lName = lName;
 }
 public String fName;
 public String lName;
 public Gender gender;
 
 public String getName(){
  return getfName()+" "+getlName();
 }
 
@Override
public String toString() {
 return  getfName()+" "+getlName();
}

}


and create person and display names

public static void main(String[] args) {
  // TODO Auto-generated method stub

    List<Person> persons=new ArrayList<>();
    persons.add(new Person("Arnolad", "Jones", Gender.MALE));
    persons.add(new Person("Zack", "Jones", Gender.MALE));
    persons.add(new Person("Mary", "Jones", Gender.FEMALE));
    persons.add(new Person("Anna", "Jones", Gender.FEMALE));
    
    System.out.println(persons.stream()
                        .sorted((p1,p2)->p1.getName().compareTo(p2.getName()))
                        .collect(Collectors.groupingBy(Person::getGender))
                        
      );
    
    
 }


Output:
{FEMALE=[Anna Jones, Mary Jones], MALE=[Arnolad Jones, Zack Jones]}

Happy Coding!!!


0 comments:

Post a Comment