Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/sorting/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何按属性排序HashMap_Java_Sorting_Hashmap_Comparable - Fatal编程技术网

Java 如何按属性排序HashMap

Java 如何按属性排序HashMap,java,sorting,hashmap,comparable,Java,Sorting,Hashmap,Comparable,正如您可能已经知道的,当您将某个内容放入HashMap时,其存储顺序是随机的。我想用Comparable命令HashMap,但我无法让它正常工作 这样我就有了一张地图: Map myObjectMap=newhashmap() 这个映射的键是一个由多个id和名称(MyKeyObject)组成的结构,我想首先根据id对映射的键进行排序,如果id相同,则根据名称对映射进行排序 以下是我尝试过的: public class MyKeyObject implements Comparable<My

正如您可能已经知道的,当您将某个内容放入HashMap时,其存储顺序是随机的。我想用Comparable命令HashMap,但我无法让它正常工作

这样我就有了一张地图:

Map myObjectMap=newhashmap()

这个映射的键是一个由多个id和名称(MyKeyObject)组成的结构,我想首先根据id对映射的键进行排序,如果id相同,则根据名称对映射进行排序

以下是我尝试过的:

public class MyKeyObject implements Comparable<MyKeyObject> {
  private Long id;
  private String name;

  public MyKeyObject(Long id, String name) {
        this.id = id;
        this.name = name;
    }

  public boolean equals(Long id, String name) {
        return this.id.equals(id) && this.name.equals(name)
    }

  @Override
  public int compareTo(MyKeyObject myKeyObject) {       
      if (this.id myKeyObject.getId() != 0) {
          return (this.Id - myKeyObject.getId() == 1) ? 1 : -1;
      } else {
          return (this.name().compareTo(myKeyObject.name()) == 1) ? 1 : -1;
      }
  }

  @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        MyKeyObject that = (MyKeyObject) o;
        return id.equals(that.id) &&
                name == that.name;
    }

    @Override
    public int hashCode() {
        return Objects.hash(id, name);
    }
}
公共类MyKeyObject实现了可比较的{
私人长id;
私有字符串名称;
公共MyKeyObject(长id,字符串名称){
this.id=id;
this.name=名称;
}
公共布尔等于(长id、字符串名称){
返回this.id.equals(id)&&this.name.equals(name)
}
@凌驾
public int compareTo(MyKeyObject MyKeyObject){
if(this.id myKeyObject.getId()!=0){
返回(this.Id-myKeyObject.getId()==1)?1:-1;
}否则{
返回(this.name().compareTo(myKeyObject.name())==1)?1:-1;
}
}
@凌驾
公共布尔等于(对象o){
如果(this==o)返回true;
如果(o==null | | getClass()!=o.getClass())返回false;
MyKeyObject,该对象=(MyKeyObject)o;
return id.equals(that.id)&&
name==that.name;
}
@凌驾
公共int hashCode(){
返回Objects.hash(id,name);
}
}
公共类MyKeyObject实现了可比较的{
Map myObjectMap=新建HashMap();
//这里我有很多填充HashMap的代码
myObjectMap.entrySet().stream().sorted(Map.Entry.comparingByKey());
}
老实说,我甚至不认为compareTo方法被击中,我做错了什么


更新:我知道有像TreeMap这样的类型,但它不适合我。我刚刚给出了一个非常简单的示例,我的实际代码非常复杂。有没有可能像我在这里尝试过的那样,用类似的方法来完成这项工作

我想你要找的不是HashMap

这里有一个用例的简化示例

import java.util.Comparator;
import java.util.Map;
import java.util.Objects;
import java.util.TreeMap;

public class TreeMapExample {
    public static void main(String[] args) {
        Map<MyKeyObject, Object> myTreeMap = new TreeMap<>();

        myTreeMap.put(new MyKeyObject(5L, "Jay"), null);
        myTreeMap.put(new MyKeyObject(5L, "Bob"), null);
        myTreeMap.put(new MyKeyObject(1L, "Alison"), null);
        myTreeMap.put(new MyKeyObject(3L, "Frey"), null);

        myTreeMap.entrySet()
                .forEach(myKeyObjectObjectEntry ->
                        System.out.println(String.format(
                                "Id= %s, Name=%s",
                                myKeyObjectObjectEntry.getKey().id,
                                myKeyObjectObjectEntry.getKey().name )));
    }

    public static class MyKeyObject implements Comparable<MyKeyObject> {
        private Long id;
        private String name;

        public MyKeyObject(Long id, String name) {
            this.id = id;
            this.name = name;
        }

        @Override
        public int compareTo(MyKeyObject myKeyObject) {
            return Comparator.comparing((MyKeyObject keyObject)->keyObject.id)
                    .thenComparing(keyObject->keyObject.name)
                    .compare(this, myKeyObject);
        }

    }
}

您可以将
MyKeyObject
设置为可比较的,或将提供程序设置为树映射的比较器。

HashMap
没有定义顺序,因此尝试对其进行排序是不可能的。您是否尝试使用
LinkedHashMap
而不是HashMap?哈希映射永远不会包含顺序。LinkedHashMap保持插入顺序。@scigs a
SortedMap
类似于
TreeMap
可能是一个更好的选择。正如Andy所说,
HashMap
没有定义的顺序,但更进一步,流API不是更改集合的工具。行
myObjectMap.entrySet().stream().sorted(Map.Entry.comparingByKey())无效,因为它缺少实际操作。
import java.util.Comparator;
import java.util.Map;
import java.util.Objects;
import java.util.TreeMap;

public class TreeMapExample {
    public static void main(String[] args) {
        Map<MyKeyObject, Object> myTreeMap = new TreeMap<>();

        myTreeMap.put(new MyKeyObject(5L, "Jay"), null);
        myTreeMap.put(new MyKeyObject(5L, "Bob"), null);
        myTreeMap.put(new MyKeyObject(1L, "Alison"), null);
        myTreeMap.put(new MyKeyObject(3L, "Frey"), null);

        myTreeMap.entrySet()
                .forEach(myKeyObjectObjectEntry ->
                        System.out.println(String.format(
                                "Id= %s, Name=%s",
                                myKeyObjectObjectEntry.getKey().id,
                                myKeyObjectObjectEntry.getKey().name )));
    }

    public static class MyKeyObject implements Comparable<MyKeyObject> {
        private Long id;
        private String name;

        public MyKeyObject(Long id, String name) {
            this.id = id;
            this.name = name;
        }

        @Override
        public int compareTo(MyKeyObject myKeyObject) {
            return Comparator.comparing((MyKeyObject keyObject)->keyObject.id)
                    .thenComparing(keyObject->keyObject.name)
                    .compare(this, myKeyObject);
        }

    }
}
Id=1, Name=Alison
Id=3, Name=Frey
Id=5, Name=Bob
Id=5, Name=Jay