[英]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.