[英]Java:Sorting an arraylist having linkedlist with the first element
將此數組列表與鏈表對象一起考慮(are-> 1-> 3-> 7,croco-> 4-> 1,bat-> 3-> 8)。
現在,我必須考慮到arraylist中包含的鏈表的第一個元素,以升序對Java中的arraylist進行排序。 有一個Collections.sort()方法,但是當對象是字符串時,它很有用。 在這種情況下應采取什么措施? 最終列表應如下所示(are-> 1-> 3-> 7,bat-> 3-> 8,croco-> 4-> 1)
Collections.sort();
有一個采用比較器的重載方法。 所以你想要這樣的東西:
Collections.sort(lists, (o1, o2) ->
o1.get(0).compareTo(o2.get(0))
);
或者,如果可以使用Java 8,則List
接口中有一個默認的sort
方法:
lists.sort(Comparator.comparing(o -> o.get(0)));
沒有太多背景,我可能是錯的。 但是,根據我的判斷,如果您正在使用包含標識符(are,croco和bat)和鏈表(數字)的自己的對象,則可以使用以下解決方案。
您的類需要實現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.