0

I try to sort a Linked list of HashMaps by key


Wanted output:

[{Addres=Astreet, Name=Aron}, {Addres=Bstreet, 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);
4
  • Don't use Map but your own class, which has instance fields for Addres and Name Commented Mar 13, 2020 at 12:13
  • I'd take a look at docs.oracle.com/javase/8/docs/api/java/util/Comparator.html Commented Mar 13, 2020 at 12:13
  • Does this answer your question? How to sort Map values by key in Java? Commented Mar 13, 2020 at 12:13
  • @akuzminykh I think Op wants to sort their LinkedList not the HashMaps themselves Commented Mar 13, 2020 at 12:15

1 Answer 1

1

What you want to do is create a POJO that represents these entries and store them in a List. Then you can sort that list based on criteria like name or address.

        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());
Sign up to request clarification or add additional context in comments.

Comments

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.