首页 > 解决方案 > 按值对 LinkedList 进行排序

问题描述

我有一个链表结构,每个节点都存储int ID号、字符串名称变量和节点链接变量。我想根据 ID 对这个列表进行升序排序。collection.sort 适合这个吗?我该如何实际处理?

标签: javasortinglinked-list

解决方案


您有两种选择:

  1. 让你的 Node 类实现Comparable 接口并实现compareTo(NodeType other)如下return Integer.compare(this.id, other.id)

  2. 在您的 LinkedList 上使用Collections.sort自定义比较器: Collections.sort(list, (a,b) -> Integer.compare(a.getId(),b.getId()).


推荐阅读