简体   繁体   English

如何在 Java 中对项目进行排序

[英]How to sort items on entry in Java

Let us say we have been given a list of letters B,F,A,G and that they are stacked upon one another and I want to print out the order in which they were stacked in. For example if I was given the information that:假设我们得到了一份字母 B、F、A、G 的列表,它们相互堆叠,我想打印出它们堆叠的顺序。例如,如果我得到的信息是:

AG / FB / AB / AF / GB / GF AG / FB / AB / AF / GB / GF

where the symbol - means "is on top of" (so A is on top of G, F is on top of B, A is on top of B...) then I want to output A, G, F, B based on the given data.其中符号 - 表示“位于”之上(因此 A 位于 G 之上,F 位于 B 之上,A 位于 B 之上......)那么我想要基于 output A,G,F,B在给定的数据上。 The problem is that this list is read line by line so after line one is read the expected output is A, G until other lines are read and the expected output is updated.问题是这个列表是逐行读取的,所以在读取第一行之后,预期的 output 是 A,G,直到读取其他行并更新预期的 output。 My first instinct was to use stack but then I would require a lot of pop and push operations and would be a hassle because the best data structure would allow me to switch places between letters or move things around freely and trees seem to be the best option but how exactly would this be implemented?我的第一直觉是使用堆栈,但随后我需要大量的弹出和推送操作,这会很麻烦,因为最好的数据结构将允许我在字母之间切换位置或自由移动东西,而树似乎是最好的选择但这将如何实施呢?

I would use a directed graph.我会使用有向图。 There are no directed graph classes in the JDK, but there are many libraries that implement it (listed here ), I would personally look at jgrapht or Google's Guava library (do not remember if there is a directed graph). JDK中没有有向图类,但是有很多实现它的库(这里列出),我个人会看jgrapht或者谷歌的Guava库(不记得有没有有向图)。 This is what a directed graph for your data looks like:这是您数据的有向图的样子:
有向图

Once your directed graph is created, and you ensure it has no cycles (for example, you did not define AB, BC, CA, which creates a cycle), then sorting is a just a matter of writing a comparator with the following logic:一旦创建了有向图,并确保它没有环路(例如,您没有定义 AB、BC、CA,这会创建环路),那么排序就是使用以下逻辑编写比较器的问题:

  • if o1 == o2 return 0;如果 o1 == o2 返回 0;
  • if o1 is connected to o2 return -1;如果 o1 连接到 o2,则返回 -1;
  • if o1 is not connected to o2 return 1;如果 o1 没有连接到 o2,则返回 1;

You can use the pairs to construct a comparator like this:您可以使用这些对来构造一个比较器,如下所示:

Set<List<String>> pairs = Arrays.stream(order.split(" / "))
        .map(p -> p.split("-"))
        .map(Arrays::asList)
        .collect(Collectors.toSet());

Comparator<String> compare = (a, b) ->
        pairs.contains(Arrays.asList(a, b)) ? -1 :
        pairs.contains(Arrays.asList(b, a)) ? 1 :
        0;

Then use that to sort your input in whatever structure you want.然后使用它以您想要的任何结构对您的输入进行排序。

Ideone Demo创意演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM