Java 在新的 hashmap 中对参数进行排序而不是返回到 main

Java Sorting parameters in a new hashmap than returning to main

我正在做一个 KNN 项目,我正在尝试对我在新哈希图中计算出的欧几里得距离和索引进行排序,然后将它们带回我的主节点。这是我对距离进行排序的代码。但是,public int compare() 函数仅 returns int,我不能将其设置为 public double compare(),因为我所有的距离都是双倍的,所以我不能使用这个函数。我将不胜感激任何帮助,非常感谢。

HashMap<Integer, KnnBundle> knnBundleHashMap = new HashMap<Integer, knnBundle>();

// cnt is the size
for(int i = 0; i< cnt; i++){
knnBundleHaspMap.put(i, newKnnBundle(xarray[i], yarray[i], classes[i], euclid[i]);
}

// not yet sorted
List<KNNBundle>sortedEuclid = new ArrayList<knnBundle>(knnBundleHaspMap.values());

Collections.sort(sortedEuclid, new Comparator<KNNBundle>() {

    public int compare(KNNBundle o1, KNNBundle o2) {
        return o1.getEuclid2() - o2.getEuclid2();
    }
});

使用Double.compare:

return Double.compare(o1.getEuclid2(), o2.getEuclid2());

一般来说,您不应该在比较方法中使用减法,因为它不能正确处理溢出、正零与负零、NaN 等问题

在 Java 8+ 中,你可以更容易地写成:

   List<KNNBundle>sortedEuclid =
       knnBundleHaspMap.values()
           .stream()
           .sorted(Comparator.comparingDouble(KNNBundle::getEuclid2))
           .collect(Collectors.toList());

有多种方法可以解决这个问题。 在 Java 8 或更高版本中:

List sorted = knnBundleHaspMap.values().stream().sort((b1, b2) -> Double.compare(b1.Euclid2(), b2.Euclid2()).collect(Collectors.toList());

使用您创建的比较器,只需将比较函数的内容替换为:

Double.compare(b1.Euclid2(), b2.Euclid2())
Collections.sort(sortedEuclid, new Comparator<KNNBundle>() {

    public int compare(KNNBundle o1, KNNBundle o2) {
        return o1.getEuclid2() > o2.getEuclid2() ? 1 : o1.getEuclid2() < o2.getEuclid2() ? -1 : 0;
    }
});

如果JAVA8

For Ascending

  Comparator comparator = Comparator.comparing(KNNBundle::getEuclid2);
  Collections.sort(sortedEuclid,comparator);

For Descending

Comparator comparator = Comparator.comparing(KNNBundle::getEuclid2).reversed();
Collections.sort(sortedEuclid,comparator);

如果JAVA 7 并且JAVA 6

Collections.sort(sortedEuclid, new Comparator<KNNBundle>() {

    public int compare(KNNBundle o1, KNNBundle o2) {
        return o1.getEuclid2().compareTo(o2.getEuclid2());
    }
});