我有这个LinkedHashMap,其中包含整数索引和对象Paire的值:
Map<Integer, Paire> population1 = new LinkedHashMap<>();
我的 Paire 类相当简单,看起来像这样:
public class Paire {
float valeur;
int index;
public Paire(LinkedList<Sommet> liste, float valeur, int index) {
this.liste = liste;
this.valeur = valeur;
this.index = index;
}
现在我想将我的映射的一个键集存储在一个 LinkedList 中,按我的类 (valeur( 中的浮点值排序:
List<Integer> selection1 = new LinkedList(population1.keySet());
我知道我可以使用 Collection.sort 对值进行排序,然后如果这些值是简单的字符串或数字,则追溯它们各自的键,但我在这里有点迷茫。 我觉得有一些简单快捷的方法可以在没有中间列表和变量的情况下做到这一点。此外,我的代码的执行需要尽可能快(TSP 的遗传算法(。
Collections.sort(selection1, new Comparator<Integer>() {
@Override public int compare(Integer key1, Integer key2) {
return Float.compare(
population1.get(key1).valeur, population1.get(key2).valeur);
}
});
但是,如果您关心速度,LinkedList
永远不会成为您的朋友。 使用ArrayList
.
我建议使用stream(在我看来,它应该比Collections.sort快得多(:
List<Integer> list = population1.entrySet().stream().sorted((e1, e2) -> Float.
compare(e1.getValue().valeur,e2.getValue().valeur)).map(Map.Entry::getKey)
.collect(Collectors.toList());
我做了很多getFirst((和removeFirst((,这就是我使用的原因 链接列表。
更好地恢复 ArrayList 的顺序,您可以使用:
list.get(list.size() - 1)
而不是
getFirst()
和
list.remove(list.size() - 1)
而不是
removeFirst()
因为获取和删除 ArrayList 的最后一个元素非常非常快。
附言LinkedList几乎在任何情况下都非常非常慢