java list<string> 排序_如何对List <String>重新排序

博客介绍了在Java中使用TreeSet对Locale列表进行去重和排序的方法。通过自定义Comparator,消除重复的国家项,并对美国和英国等优先地区进行排序。代码展示了如何收集所有可用的Locale,将其添加到TreeSet中,最后将结果转换为List输出。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

小编典典

您还可以使用TreeSet来消除重复项,并使用自己来消除ComparatorUS和GB。

由于每个国家/地区通常有多个区域设置,因此您会得到重复(这将消除这种情况)。有一个美国(西班牙)和一个美国(英语),例如三个瑞士(法国,德国和意大利)。

public class AllLocales {

// Which Locales get priority.

private static final Locale[] priorityLocales = {

Locale.US,

Locale.UK

};

private static class MyLocale implements Comparable {

// My Locale.

private final Locale me;

public MyLocale(Locale me) {

this.me = me;

}

// Convenience

public String getCountry() {

return me.getCountry();

}

@Override

public int compareTo(MyLocale it) {

// No duplicates in the country field.

if (getCountry().equals(it.getCountry())) {

return 0;

}

// Check for priority ones.

for (int i = 0; i < priorityLocales.length; i++) {

Locale priority = priorityLocales[i];

// I am a priority one.

if (getCountry().equals(priority.getCountry())) {

// I come first.

return -1;

}

// It is a priority one.

if (it.getCountry().equals(priority.getCountry())) {

// It comes first.

return 1;

}

}

// Default to straight comparison.

return getCountry().compareTo(it.getCountry());

}

}

public static List listAll() {

Set byLocale = new TreeSet();

// Gather them all up.

for (Locale locale : Locale.getAvailableLocales()) {

final String isoCountry = locale.getDisplayCountry();

if (isoCountry.length() > 0) {

//System.out.println(locale.getCountry() + ":" + isoCountry + ":" + locale.getDisplayName());

byLocale.add(new MyLocale(locale));

}

}

// Roll them out of the set.

ArrayList list = new ArrayList<>();

for (MyLocale l : byLocale) {

list.add(l.getCountry());

}

return list;

}

public static void main(String[] args) throws InterruptedException {

// Some demo usages.

List locales = listAll();

System.out.println(locales);

}

}

2020-10-27

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值