sort the hash map value based on condition
本问题已经有最佳答案,请猛点这里访问。
将患者类别值存储在hashmap中,如下所示。
1 2 3 4 5 | { 0=Patient [patientName=Robert, phoneNumber=9878594302, age=30], 1=Patient [patientName=mathew, phoneNumber=9876643278, age=56], 2=Patient [patientName=smith, phoneNumber=87, age=8334456781] } |
根据年龄,要显示哈希映射值?
怎么可能?
是的,这是可能的,请参阅下面的代码片段。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | 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); } |
患者实体
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | 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 + '}'; } } |
号