-1

Storing the patient class value in Hashmap like this.

{
0=Patient [patientName=Robert, phoneNumber=9878594302, age=30], 
1=Patient [patientName=mathew, phoneNumber=9876643278, age=56], 
2=Patient [patientName=smith, phoneNumber=87, age=8334456781]
}

Based on age, want to display the descending and ascending order of the hash map value?

how is it possible ?

Nagaraj
  • 1
  • 1
  • 6

1 Answers1

0

Yes, it is possible, see the snippet below.

public static void main(String[] args) {
    Map<Integer, Patient> patients = new HashMap<>();

    patients.put(0, new Patient("btest", 12));
    patients.put(1, new Patient("atest", 11));
    patients.put(2, new Patient("dtest", 10));
    patients.put(3, new Patient("ctest", 13));

    System.out.println("Ascending");
    patients
            .values()
            .stream()
            .sorted(Comparator.comparing(Patient::getAge))
            .forEach(System.out::println);

    System.out.println("Descending");
    patients
            .values()
            .stream()
            .sorted(Comparator.comparing(Patient::getAge).reversed())
            .forEach(System.out::println);
}

Patient entity

class Patient {

    private String name;
    private Integer age;

    public Patient(String name, Integer age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Patient{" +
               "name='" + name + '\'' +
               ", age=" + age +
               '}';
    }
}