简体   繁体   English

Java:排序第一个元素具有链表的数组列表

[英]Java:Sorting an arraylist having linkedlist with the first element

Consider this arraylist with linkedlist objects (are->1->3->7 , croco-> 4 ->1 , bat ->3->8). 将此数组列表与链表对象一起考虑(are-> 1-> 3-> 7,croco-> 4-> 1,bat-> 3-> 8)。
Now I have to sort the arraylist in java in ascending order considering the first element of linkedlist contained in arraylist. 现在,我必须考虑到arraylist中包含的链表的第一个元素,以升序对Java中的arraylist进行排序。 There is a method Collections.sort() but it is useful when objects are strings. 有一个Collections.sort()方法,但是当对象是字符串时,它很有用。 What to apply in this situation? 在这种情况下应采取什么措施? The final list should look something like this (are->1->3->7 , bat ->3->8 , croco-> 4 ->1 ) 最终列表应如下所示(are-> 1-> 3-> 7,bat-> 3-> 8,croco-> 4-> 1)

Collections.sort(); has an overloaded method that takes a comparator as well. 有一个采用比较器的重载方法。 So you want something like this: 所以你想要这样的东西:

Collections.sort(lists, (o1, o2) ->
        o1.get(0).compareTo(o2.get(0))
);

Or if you can use Java 8, there is a default sort method in List interface: 或者,如果可以使用Java 8,则List接口中有一个默认的sort方法:

lists.sort(Comparator.comparing(o -> o.get(0)));

Without much context, I might be wrong. 没有太多背景,我可能是错的。 However, from my judgement if you're using your own objects which contain an identifier (are, croco and bat), and a linkedlist(numbers), then you can use the following solution. 但是,根据我的判断,如果您正在使用包含标识符(are,croco和bat)和链表(数字)的自己的对象,则可以使用以下解决方案。

Your class needs to implement the Comparable Interface You need to override the compareTo() method Collections.sort() should sort your objects in ascending order. 您的类需要实现Comparable接口,您需要重写compareTo()方法Collections.sort()应该将对象按升序排序。

public class Example implements Comparable {
    private String identifier;
    private List<Integer> list;

    // constructors
    // getters

    @Override
    public int compareTo(Object other){ 
    if(this.list.head() > other.list.head()) return 1; 
    if(this.list.head() < other.list.head()) return -1;
    else return 0;
    }
}

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

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