我尝试按键对HashMap的链接列表进行排序
想要的输出:
[{Addres = A Street,Name = Aron},{Address = Street,Name = Bernie},{Addres = Cstreet,Name = Carol}}

  //Making Contacts

        HashMap contact1 = new HashMap();
        HashMap contact2 = new HashMap();
        HashMap contact3 = new HashMap();


        contact1.put("Name", "Bernie");
        contact1.put("Addres", "Bstreet");


        contact2.put("Name", "Aron");
        contact2.put("Addres", "Astreet");


        contact3.put("Name", "Carol");
        contact3.put("Addres", "Cstreet");


   //Making ContactBook

        LinkedList contactBook = new LinkedList();

        contactBook.add(contact1);
        contactBook.add(contact2);
        contactBook.add(contact3);


        System.out.println(contactBook);

最佳答案

您要做的是创建一个代表这些条目的POJO,并将它们存储在List中。然后,您可以根据名称或地址等条件对该列表进行排序。

        class Person {

            private final String name;

            private final String address;

            Person(String name, String address) {
                this.name = name;
                this.address = address;
            }

            public String getName() {
                return name;
            }

            public String getAddress() {
                return address;
            }

            @Override
            public String toString() {
                return String.format("name=%s, address=%s", name, address);
            }
        }

        List<Person> people = new ArrayList<>(Arrays.asList(
             new Person("Bernie", "Bstreet"),
             new Person("Aron", "Astreet"),
             new Person("Carol", "Cstreet")
        ));

        List<Person> sortedByName = people.stream()
                .sorted(Comparator.comparing(Person::getName))
                .collect(Collectors.toList());

        List<Person> sortedByAddress = people.stream()
                .sorted(Comparator.comparing(Person::getAddress))
                .collect(Collectors.toList());

关于java - 如何在Java中按键对 map 列表进行排序?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/60670231/

10-11 16:28