【问题标题】:How to sort ArrayList alphabetically by fields that contain non-english characters? Java如何按包含非英文字符的字段按字母顺序对 ArrayList 进行排序?爪哇
【发布时间】:2021-04-25 22:11:22
【问题描述】:

我有一个要按字母顺序排序的自定义对象的 ArrayList。问题是我想要对其进行排序的字段有时包含非英文字符,例如áé。 我想通过使用Collections.sort() 来做到这一点,但是使用这种方法,字段中包含非英语字符串的项目无法正确排序。

这是我尝试过的:

public List<Video> sortDatabase(List<Video> videos){
        List<Video> sortedList = new ArrayList<>(videos);
        Collections.sort(sortedList, new Comparator<Video>() {
            @Override
            public int compare(Video video, Video t1) {
                return video.getTitle().compareTo(t1.getTitle());
            }
        });
        return orderedList;
    }

编辑
我正在使用带有minSdkVersion 21的Android Studio

【问题讨论】:

    标签: java arrays sorting arraylist collections


    【解决方案1】:

    我找到了一个很好的答案here。这就是我的情况:

    public List<Video> sortDatabase(List<Video> videos){
            List<Video> sortedList = new ArrayList<>(videos);
            orderedList.sort(new VideoComparator());
            return orderedList;
        }
    
    private static class VideoComparator implements Comparator<Video>{
                Collator spCollator = Collator.getInstance(new Locale("hu", "HU"));
                public int compare (Video e1, Video e2){
                    return spCollator.compare(e1.getTitle(), e2.getTitle());
                }
            }
    

    就我而言,必须使用("hu", "HU") 构建语言环境。您可以查看所有支持的语言here

    此解决方案工作正常,但是,我尝试将其用于 Android 应用程序,该方法仅适用于 API 级别 24 或更高级别。因此,如果有人有不同的解决方案,我会将其作为公认的答案。

    【讨论】:

    • 您不需要手动实现比较器。只需使用orderedList.sort( Comparator.comparing(Video::getTitle, Collator.getInstance(new Locale("hu", "HU")));
    【解决方案2】:

    但使用此方法,字段中包含非英语(原文如此)字符串的项目无法正确排序。

    你确定是这个问题吗?会不会是你不明白排序涉及什么?我很确定问题出在字符的 Unicode 值上。字符按字符集组织。整个英语语言字符的 Unicode 值低于或高于其他语言的字符,从而给人以排序错误的印象。

    也许你应该看看Unicode chart 以完全理解我在说什么。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-10-26
      • 2017-05-22
      • 1970-01-01
      • 2019-02-03
      • 2011-01-04
      • 2016-03-11
      • 2013-10-28
      • 2019-05-10
      相关资源
      最近更新 更多