按字母顺序对对象的 ArrayList 进行排序 [英] Sorting an ArrayList of Objects alphabetically

查看:36
本文介绍了按字母顺序对对象的 ArrayList 进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须创建一个方法,根据电子邮件按字母顺序对 ArrayList 对象进行排序,然后打印排序后的数组.我在整理它时遇到问题的部分.我已经研究过它并尝试使用 Collections.sort(vehiclearray); 但这对我不起作用.我是我需要一个叫做比较器的东西,但不知道它是如何工作的.我是否必须使用这些,或者诸如冒泡排序或插入排序之类的东西可以用于此类事情吗?

I have to create a method that sorts an ArrayList of objects alphabetically according to email and then prints the sorted array. The part that I am having trouble with it sorting it. I have researched it and tried using Collections.sort(vehiclearray); but that didn't work for me. I was that I needed something called a comparator but couldn't figure out how it worked. Will I have to use those or can something like bubble sort or insertion sort work for this kind of thing?

这是我目前的代码:

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来完成.

The sorting part can be done by implementing a custom Comparator<Vehicle>.

Collections.sort(vehiclearray, new Comparator<Vehicle>() {
    public int compare(Vehicle v1, Vehicle v2) {
        return v1.getEmail().compareTo(v2.getEmail());
    }
});

这个匿名类将用于根据对应电子邮件的字母顺序对 ArrayList 中的 Vehicle 对象进行排序.

This anonymous class will be used for sorting the Vehicle objects in the ArrayList on the base of their corresponding emails alphabetically.

升级到 Java8 还可以让您使用方法引用以更简洁的方式实现这一点:

Upgrading to Java8 will let you also implement this in a less verbose manner with a method reference:

Collections.sort(vehiclearray, Comparator.comparing(Vehicle::getEmail));

这篇关于按字母顺序对对象的 ArrayList 进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆