[英]Sorting an ArrayList of Objects alphabetically
我必須創建一個方法,根據電子郵件按字母順序對對象的ArrayList進行排序,然后打印排序的數組。 我在排序它時遇到麻煩的部分。 我研究了它並嘗試使用Collections.sort(vehiclearray);
但這對我不起作用。 我是因為我需要一種稱為比較器的東西,但無法弄清楚它是如何工作的。 我是否必須使用這些或者可以像冒泡排序或插入排序工作這樣的東西?
這是我到目前為止的代碼:
public static void printallsort(ArrayList<vehicle> vehiclearray){
ArrayList<vehicle> vehiclearraysort = new ArrayList<vehicle>();
vehiclearraysort.addAll(vehiclearray);
//Sort
for(int i = 0; i < vehiclearraysort.size(); i++)
if ( vehiclearray.get(i).getEmail() > vehiclearray.get(i+1).getEmail())
//Printing
for(i = 0; i < vehiclearraysort.size(); i++)
System.out.println( vehiclearraysort.get(i).toString() + "\n");
}
排序部分可以通過實現自定義Comparator<Vehicle>
來完成。
Collections.sort(vehiclearray, new Comparator<Vehicle>() {
public int compare(Vehicle v1, Vehicle v2) {
return v1.getEmail().compareTo(v2.getEmail());
}
});
此匿名類將用於按字母順序在其對應的電子郵件的基礎上對ArrayList
的Vehicle
對象進行排序。
升級到Java8還可以通過方法引用以更簡潔的方式實現它:
Collections.sort(vehiclearray, Comparator.comparing(Vehicle::getEmail));
雖然這個問題已經有了公認的答案,但我想分享一些Java 8解決方案
// if you only want to sort the list of Vehicles on their email address
Collections.sort(list, (p1, p2) -> p1.getEmail().compareTo(p2.getEmail()));
。
// sort the Vehicles in a Stream
list.stream().sorted((p1, p2) -> p1.getEmail().compareTo(p2.getEmail()));
。
// sort and print with a Stream in one go
list.stream().sorted((p1, p2) -> p1.getEmail().compareTo(p2.getEmail())).forEach(p -> System.out.printf("%s%n", p));
。
// sort with an Comparator (thanks @Philipp)
// for the list
Collections.sort(list, Comparator.comparing(Vehicle::getEmail));
// for the Stream
list.stream().sorted(Comparator.comparing(Vehicle::getEmail)).forEach(p -> System.out.printf("%s%n", p));
在此鏈接中,您可以找到有助於按降序和升序對對象的arraylist進行排序的代碼。
http://beginnersbook.com/2013/12/java-arraylist-of-object-sort-example-comparable-and-comparator/
包srikanthdukuntla;
import java.util.ArrayList; import java.util.List;
公共類AlphabetsOrder {
public static void main(String[] args) {
String temp;
List<String> str= new ArrayList<String>();
str.add("Apple");
str.add("zebra");
str.add("Umberalla");
str.add("banana");
str.add("oxo");
str.add("dakuntla");
str.add("srikanthdukuntla");
str.add("Dukuntla");
for(int i=0;i<str.size();i++){
for(int j=i+1;j<str.size();j++){
if(str.get(i).compareTo(str.get(j))<0){
temp=str.get(i);
str.set(i, str.get(j));
str.set(j,temp );
}
}
}
System.out.println("List of words in alphabetical order "+str);
}
}
最明顯
vehiclearray.sort(Comparator.comparing(Vehicle::getEmail()));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.