在哈希映射中排序 [英] Sorting in Hash Maps

查看:157
本文介绍了在哈希映射中排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要熟悉集合。我有一个字符串,它是我的键,电子邮件地址和一个Person对象(firstName,lastName,电话,电子邮件)。我在Java的收集章节阅读了Sun的网页,如果你有一个HashMap,并希望它排序,你可以使用一个TreeMap。这是怎么回事?它是基于在你的Person类中有compareTo()方法吗?我覆盖我的Person类中的compareTo()方法按lastName排序。但它不能正常工作,想知道我是否有正确的想法或不。这个代码底部的getSortedListByLastName是我尝试转换为TreeMap的地方。另外,如果这是正确的方法,或者正确的方法之一,我如何排序firstName,因为我的compareTo()是比较lastName。

I'm trying to get familiar with Collections. I have a String which is my key, email address, and a Person object (firstName, lastName, telephone, email). I read in the Java collections chapter on Sun's webpages that if you had a HashMap and wanted it sorted, you could use a TreeMap. How does this sort work? Is it based on the compareTo() method you have in your Person class? I overrode the compareTo() method in my Person class to sort by lastName. But it isn't working properly and was wondering if I have the right idea or not. getSortedListByLastName at the bottom of this code is where I try to convert to a TreeMap. Also, if this is the correct way to do it, or one of the correct ways to do it, how do I then sort by firstName since my compareTo() is comparing by lastName.

import java.util.*;

public class OrganizeThis 
{
    /** 
    Add a person to the organizer

    @param p A person object
    */
    public void add(Person p)
    {   
        staff.put(p.getEmail(), p);
        //System.out.println("Person " + p + "added");
    }

    /**
    * Remove a Person from the organizer.
    *
    * @param email The email of the person to be removed.
    */
    public void remove(String email)
    {
        staff.remove(email);
    }

    /**
    * Remove all contacts from the organizer.
    *
    */
    public void empty()
    {
        staff.clear();
    }

    /**
    * Find the person stored in the organizer with the email address.
    * Note, each person will have a unique email address.
    * 
    * @param email The person email address you are looking for.
    *
    */
    public Person findByEmail(String email)
    {
        Person aPerson = staff.get(email);
        return aPerson;
    }

    /**
    * Find all persons stored in the organizer with the same last name.
    * Note, there can be multiple persons with the same last name.
    * 
    * @param lastName The last name of the persons your are looking for.
    *
    */
    public Person[] find(String lastName)
    {
        ArrayList<Person> names = new ArrayList<Person>();

        for (Person s : staff.values())
        {
            if (s.getLastName() == lastName) {
                names.add(s);
            }
        }
        // Convert ArrayList back to Array
        Person nameArray[] = new Person[names.size()];
        names.toArray(nameArray);
        return nameArray;
    }

    /**
    * Return all the contact from the orgnizer in
    * an array sorted by last name.
    * 
    * @return An array of Person objects.
    *
    */
    public Person[] getSortedListByLastName()
    {
        Map<String, Person> sorted = new TreeMap<String, Person>(staff);
        ArrayList<Person> sortedArrayList = new ArrayList<Person>();
        for (Person s: sorted.values()) {
            sortedArrayList.add(s);
        }
        Person sortedArray[] = new Person[sortedArrayList.size()];
        sortedArrayList.toArray(sortedArray);
        return sortedArray;
    }

    private Map<String, Person> staff = new HashMap<String, Person>();

public static void main(String[] args)
    {
        OrganizeThis testObj = new OrganizeThis();
        Person person1 = new Person("J", "W", "111-222-3333", "JW@ucsd.edu");
        Person person2 = new Person("K", "W", "345-678-9999", "KW@ucsd.edu");
        Person person3 = new Person("Phoebe", "Wang", "322-111-3333", "phoebe@ucsd.edu");
        Person person4 = new Person("Nermal", "Johnson", "322-342-5555", "nermal@ucsd.edu");
        Person person5 = new Person("Apple", "Banana", "123-456-1111", "apple@ucsd.edu");
        testObj.add(person1);
        testObj.add(person2);
        testObj.add(person3);
        testObj.add(person4);
        testObj.add(person5);

        System.out.println(testObj.findByEmail("JW@ucsd.edu"));
        System.out.println("------------" + '\n');

        Person a[] = testObj.find("W");

        for (Person p : a)
        System.out.println(p);

        System.out.println("------------" + '\n');
        a = testObj.find("W");

        for (Person p : a)
        System.out.println(p);

        System.out.println("SORTED" + '\n');
        a = testObj.getSortedListByLastName();
        for (Person b : a) {
            System.out.println(b);
        }
    }
    }

个人类别:

public class Person implements Comparable
{
    String firstName;
    String lastName;
    String telephone;
    String email;

    public Person()
    {
       firstName = "";
       lastName = "";
       telephone = "";
       email = "";
    }

    public Person(String firstName)
    {
        this.firstName = firstName;
    }

    public Person(String firstName, String lastName, String telephone, String email) 
    {
        this.firstName = firstName;
        this.lastName = lastName;
        this.telephone = telephone;
        this.email = email;
    }

    public String getFirstName()
    {
        return firstName;
    }

    public void setFirstName(String firstName)
    {
        this.firstName = firstName;
    }

    public String getLastName()
    {
        return lastName;
    }

    public void setLastName(String lastName)
    {
        this.lastName = lastName;
    }

    public String getTelephone()
    {
        return telephone;
    }

    public void setTelephone(String telephone)
    {
        this.telephone = telephone;
    }

    public String getEmail()
    {
        return email;
    }

    public void setEmail(String email)
    {
        this.email = email;
    }

    public int compareTo(Object o)
    {
        String s1 = this.lastName + this.firstName;
        String s2 = ((Person) o).lastName + ((Person) o).firstName;
        return s1.compareTo(s2);
    }

    public boolean equals(Object otherObject)
    {
        // a quick test to see if the objects are identical
        if (this == otherObject) {
            return true;
        }

        // must return false if the explicit parameter is null
        if (otherObject == null) {
            return false;
        }

        if (!(otherObject instanceof Person)) {
            return false;
        }

        Person other = (Person) otherObject;
        return firstName.equals(other.firstName) && lastName.equals(other.lastName) &&
            telephone.equals(other.telephone) && email.equals(other.email);
    }

    public int hashCode() 
    {
        return this.email.toLowerCase().hashCode();
    }

    public String toString()
    {
        return getClass().getName() + "[firstName = " + firstName + '\n'
                                    + "lastName = " + lastName + '\n'
                                    + "telephone = " + telephone + '\n'
                                    + "email = " + email + "]";
    }


}


推荐答案

实际上你得到了错误的想法。

You get the wrong idea, actually.

这里是gist:


  • 映射< K,V> 是从 K键 V value
  • TreeMap< K,V> SortedMap< K,V> 排序,而不是值

  • Map<K,V> is a mapping from K key to V value
  • TreeMap<K,V> is a SortedMap<K,V> that sorts the keys, not the values

,a TreeMap< String,Person> 将基于电子邮件地址进行排序,而不是 Person

So, a TreeMap<String,Person> would sort based on e-mail addresses, not the Person's first/last names.

如果您需要 SortedSet< Person> 或排序的 ; Person> 那么这是一个不同的概念,并且是, Person implements Comparable< Person> 或者 Comparator< Person>

If you need a SortedSet<Person>, or a sorted List<Person> then that's a different concept, and yes, Person implements Comparable<Person>, or a Comparator<Person> would come in handy.


  • java.lang。可比较的< T> - 定义类型的对象的自然排序

  • java.util.Comparator< T> - 定义类型对象的自定义比较

  • java.util.Map< K,V> - 将键映射到值,

  • java.util.SortedMap< K,V> - 排序键,而不是值

  • java.util.SortedSet< E> - 有序排列的集

  • java.util.Collections.sort(List) - 一种用于对


    • 进行排序的实用程序方法也有一个重载,需要一个 Comparator

    • java.lang.Comparable<T> - defines the "natural ordering" of objects of a type
    • java.util.Comparator<T> - defines a "custom" comparison of objects of a type
    • java.util.Map<K,V> - maps keys to values, not the other way around
    • java.util.SortedMap<K,V> - sorts the keys, not the values
    • java.util.SortedSet<E> - a set that is ordered
    • java.util.Collections.sort(List) - a utility method to sort
      • Also has an overload that takes a Comparator
      • When to use Comparable vs Comparator
      • Sorting a collection of objects
      • Sorting an ArrayList of Contacts
      • Java: SortedMap, TreeMap, Comparable? How to use?

      现在已经有很多例子了,但还有一个例子:

      There are plenty of examples out there already, but here's one more:

      import java.util.*;
      
      public class Example {
          static String lastName(String fullName) {
              return fullName.substring(fullName.indexOf(' ') + 1);
          }
          public static void main(String[] args) {
              Map<String,String> map = new TreeMap<String,String>();
              map.put("001", "John Doe");
              map.put("666", "Anti Christ");
              map.put("007", "James Bond");
      
              System.out.println(map);
              // "{001=John Doe, 007=James Bond, 666=Anti Christ}"
              // Entries are sorted by keys!
      
              // Now let's make a last name Comparator...
              Comparator<String> lastNameComparator = new Comparator<String>() {
                  @Override public int compare(String fullName1, String fullName2) {
                      return lastName(fullName1).compareTo(lastName(fullName2));
                  }
              };
      
              // Now let's put all names in a SortedSet...
              SortedSet<String> namesByLastName =
                  new TreeSet<String>(lastNameComparator);
              namesByLastName.addAll(map.values());
      
              System.out.println(namesByLastName);
              // "[James Bond, Anti Christ, John Doe]"
              // Names sorted by last names!
      
              // Now let's use a List instead...
              List<String> namesList = new ArrayList<String>();
              namesList.addAll(map.values());
              System.out.println(namesList);
              // "[John Doe, James Bond, Anti Christ]"
              // These aren't sorted yet...
      
              Collections.sort(namesList);
              System.out.println(namesList);
              // "[Anti Christ, James Bond, John Doe]"
              // Sorted by natural ordering!
      
              // Now let's sort by string lengths...
              Collections.sort(namesList, new Comparator<String>() {
                  @Override public int compare(String s1, String s2) {
                      return Integer.valueOf(s1.length()).compareTo(s2.length());
                  }
              });
              System.out.println(namesList);
              // "[John Doe, James Bond, Anti Christ]"
              // SUCCESS!!!
          }
      }
      

      这篇关于在哈希映射中排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆