简体   繁体   English

在Java中按值订购HashMap不起作用

[英]Order HashMap by value in Java doesn't work

I have this object: 我有这个对象:

public class Customer {

    private String id;
    private String name;
    private String cf;
    private String pi;
    private String telephone;
    private String email;
    private String website;
    private String sector;
    private String address;

    //constructor and getter, setter method

}

and a Map of Customer into main: 并将“客户地图”转换为主要内容:

Map<String, Customer> customerMap = new HashMap<>();
customerMap.put("1", customer1);
customerMap.put("2", customer2);
...

sortMapByName(customerMap);

I want to order it by name attribute. 我想按名称属性排序。

I use the solution at this link: How to sort a Map in Java 我在此链接上使用解决方案: 如何在Java中对地图进行排序

Code: 码:

public void sortMapByName(Map<String, Customer> unsortMap) {

    // Convert Map to List
    List<Map.Entry<String, Customer>> list = new LinkedList<>(unsortMap.entrySet());

    // Sort list with comparator, to compare the Map values
    Collections.sort(list, new Comparator<Map.Entry<String, Customer>>() {

        @Override
        public int compare(Map.Entry<String, Customer> o1, Map.Entry<String, Customer> o2) {
            return (o1.getValue().getName()).compareTo(o2.getValue().getName());
        }
    });

    // Convert sorted map back to a Map
    listCustomer = new LinkedHashMap<>();
    for (Map.Entry<String, Customer> entry : list) {
        listCustomer.put(entry.getKey(), entry.getValue());
    }

}

it doesn't work, why? 它不起作用,为什么?

UPDATE 更新

Please, try it. 请尝试一下。

Customer.java 客户.java

public class Customer {

private String id;
private String name;
private String cf;
private String pi;
private String telephone;
private String email;
private String website;
private String sector;
private String address;

public Customer() {
}

public Customer(String id, String name, String cf, String pi, String telephone, String email, String website, String sector, String address) {
    this.id = id;
    this.name = name;
    this.cf = cf;
    this.pi = pi;
    this.telephone = telephone;
    this.email = email;
    this.website = website;
    this.sector = sector;
    this.address = address;
}

public String getId() {
    return id;
}

public void setId(String id) {
    this.id = id;
}

public String getName() {
    return name;
}

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

public String getCf() {
    return cf;
}

public void setCf(String cf) {
    this.cf = cf;
}

public String getPi() {
    return pi;
}

public void setPi(String pi) {
    this.pi = pi;
}

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 String getWebsite() {
    return website;
}

public void setWebsite(String website) {
    this.website = website;
}

public String getSector() {
    return sector;
}

public void setSector(String sector) {
    this.sector = sector;
}

public String getAddress() {
    return address;
}

public void setAddress(String address) {
    this.address = address;
}

Main.java Main.java

public class Main { 

public static void main(String[] args) {

    Map<String, Customer> unsortedMap = new HashMap<>();

    Customer one = new Customer("1", "B", "bbb", "1234", "bbb", "gmail.com", "none", "student", "Italy");
    Customer two = new Customer("2", "C", "ccc", "1234", "ccc", "gmail.com", "none", "student", "Italy");
    Customer three = new Customer("3", "A", "aaa", "1234", "aaa", "gmail.com", "none", "student", "Italy");

    unsortedMap.put("1", one);
    unsortedMap.put("2", two);
    unsortedMap.put("3", three);

    System.out.print("Before: \n"+unsortedMap);

    Map<String, Customer> sortedMap = sortMapByName(unsortedMap);

    System.out.print("\n\nAfter: \n"+sortedMap);
}

public static Map<String, Customer> sortMapByName(Map<String, Customer> unsortMap) {

    // Convert Map to List
    List<Map.Entry<String, Customer>> list = new LinkedList<>(unsortMap.entrySet());

    // Sort list with comparator, to compare the Map values
    Collections.sort(list, new Comparator<Map.Entry<String, Customer>>() {

        @Override
        public int compare(Map.Entry<String, Customer> o1, Map.Entry<String, Customer> o2) {
            return (o1.getValue().getName()).compareTo(o2.getValue().getName());
        }
    });

    // Convert sorted map back to a Map
    Map<String, Customer> sortedMap = new LinkedHashMap<>();
    for (Iterator<Map.Entry<String, Customer>> it = list.iterator(); it.hasNext();) {
        Map.Entry<String, Customer> entry = it.next();
        sortedMap.put(entry.getKey(), entry.getValue());
    }

    return sortedMap;

}

}

You need to use the sorted map in the method. 您需要在方法中使用排序的映射。 Change the type from void to Map<String, Customer and add return listCustomer; 将类型从void更改为Map<String, Customer并添加return listCustomer; at the end. 在末尾。 The original map is simply preserved unchanged in your current code. 原始地图只是在当前代码中保留不变。

public Map<String, Customer> sortMapByName(Map<String, Customer> unsortMap) {

   ...
   return listCustomer;
}

If, for some reason, listCustomer is a class member, make sure you use that instead of the original unsorted one. 如果出于某种原因, listCustomer是类成员,请确保使用该类而不是原始的未排序成员。

UPDATE: When printing the map, you can loop over the map entries: 更新:打印地图时,您可以遍历地图条目:

for (Iterator<String> iterator = sortedMap.keySet().iterator(); iterator.hasNext();) {
    Customer cust = sortedMap.get(iterator.next());
    System.out.println(cust);   
}

You'd also need to override the toString() method in Customer to print something useful, something like: 您还需要覆盖CustomertoString()方法以打印出有用的内容,例如:

@Override
public String toString() {
    return "Customer [id=" + id + ", name=" + name + ", cf=" + cf + ", pi="
            + pi + ", telephone=" + telephone + ", email=" + email
            + ", website=" + website + ", sector=" + sector + ", address="
            + address + "]";
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM