【问题标题】:Sort chained objects with parent使用父对象对链式对象进行排序
【发布时间】:2019-06-20 10:49:46
【问题描述】:

我们有类别列表,其中每个类别都可以具有引用当前类别的父类别的父字段。你能告诉我java中对类别进行排序的最佳算法是什么,例如从上到下的类别?谢谢。

@Table
@Entity
public class Category {
     @Id
     Long id;
     @ManyToOne
     Category parent;
}

示例:

列表:

  • 类别(id=3, parent=Category(id=11))
  • 类别(id=4, parent=Category(id=3))
  • 类别(id=11, parent=Category(id=20, parent=null))

会像这样从上到下排序:

类别(id=20) -> 类别(id=11) -> 类别(id=3) -> 类别(id=4)

【问题讨论】:

  • 举个具体的例子。您要对列表或链 parent-child-grandchiled-... 进行排序吗?提供一个小例子和期望的结果。还请提及您到目前为止所做的尝试。
  • @MrSmith42 对不起.. 我添加它是为了更好地理解
  • 我在您的示例中看不到排序。您只是按照父关系已定义的顺序列出了类别。
  • @MrSmith42 我还添加了图片。我需要一些逻辑,它可以有效地创建您在图像上看到的类别顺序。从最高的父母到最低的孩子
  • 您在寻找topological sorting 吗?

标签: java algorithm sorting data-structures


【解决方案1】:

假设你已经列出了。您可以使用 Collections.sort() 对该列表进行排序; 但是你的类必须改变一点,因为你必须实现 Comparable 并覆盖 compareTo() 方法。这是一个例子,希望对你有所帮助。

public class Category implements Comparable<Category>{
    Long id;
    Category parent;
    // Constructors getters setters
    public int compareTo(Category aux){
       // Assuming you want to sort by parent's id, and I understand a category
       // maybe doesn't have parent it may be null
       if(aux.getParent() != null && this.parent != null){
           if(aux.getParent().getId() > this.parent.getId()) return -1;
           else if(aux.getParent().getId() < this.parent.getId()) return ;
           return 0;
       }
       if(aux.getParent() == null && this.parent.getId() == null) return 0;
       if(aux.parent() == null) return 1;
       return 0;
    }
}

【讨论】:

  • 如果他不想更改类,他也可以使用Comparator 而不是实现Comparable
  • 没错,这是另一种选择。
  • 我无法计算 id 大小,我用示例更新问题我的意思
【解决方案2】:

我看不到这里是如何进行排序的。

  1. 搜索没有父类的类别
  2. 搜索它的子节点
  3. 转到 2

这将为您提供所需的列表。

备注:
如果每个父母只有一个孩子或没有孩子,你会得到一个像你的例子一样的列表。 (或多个列表),否则您会得到一棵树(或多个树)。

在“一个或没有孩子”的情况下,您可以通过字段child 扩展您的类别,使其成为一个双链表。在这种情况下,“搜索它的孩子”变得微不足道,因为您可以直接引用它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-12-05
    • 1970-01-01
    • 1970-01-01
    • 2011-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多