按字母顺序排列对象的ArrayList
我必须创建一个方法,根据电子邮件按字母顺序对对象的ArrayList进行排序,然后打印排序的数组。 我正在排序它的部分。 我研究了它并尝试使用Collections.sort(vehiclearray);
但这对我不起作用。 我是因为我需要一种称为比较器的东西,但却无法弄清楚它是如何工作的。 我是否必须使用那些或者可以像冒泡排序或插入排序工作这样的东西?
这是我到目前为止的代码:
public static void printallsort(ArrayList vehiclearray){ ArrayList vehiclearraysort = new ArrayList(); vehiclearraysort.addAll(vehiclearray); //Sort for(int i = 0; i vehiclearray.get(i+1).getEmail()) //Printing for(i = 0; i < vehiclearraysort.size(); i++) System.out.println( vehiclearraysort.get(i).toString() + "\n"); }
可以通过实现自定义Comparator
来完成排序部分。
Collections.sort(vehiclearray, new Comparator() { 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 str= new ArrayList (); 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
}