按字母顺序对对象数组进行排序 [英] Sort an array of objects alphabetically

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

问题描述

我有一个对象数组,每个对象都有一个给定的名字和一个姓氏。
使用方法getGivenName和getSurname将这些名称写入对象。

I have an array of objects and each objects has a given name and a surname. These names are written to the object using methods getGivenName and getSurname.

我需要按姓氏的字母顺序对数组中的元素进行排序。
我该怎么做?

I need to sort the elements in the array in alphabetical order by surname. how can I do this?

推荐答案

你的比较器

class SampleComparator implements Comparator<YourObject> {
    @Override
    public int compare(YourObject o1, YourObject o2) {

           return o1.getSurname().compareTo(o2.getSurname());
   }
}

您的排序

  Collections.sort(YourList, new SampleComparator())

如果你需要忽略大小写然后使用

if you need ignore case then use like

  return o1.getSurname().compareToIgnoreCase(o2.getSurname()); 

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

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