如何对包含字符串数组的arraylist进行排序? [英] how to sort an arraylist that contains string arrays?

查看:107
本文介绍了如何对包含字符串数组的arraylist进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

List<String[]> allWordList = new ArrayList<>();

我想基于字符串数组中的第一个元素按字母顺序对"allWordList"列表进行排序.

I would like to sort the "allWordList" list based on the first element in string array alphabetically.

我有一个包含大小为2的字符串数组的列表.因此,基本上,我想通过比较字符串数组的第一个元素对该列表进行排序.

I have a list that contains string array which are of size 2. So basically i want to sort this list by comparing the first element of the string array.

Collection.sort();

由于用于排序而无法工作...

does not work as it is used to sort......

List<String>

而不是

List<String[]>

要清楚,我不想对单个string []元素进行排序.我想根据字符串数组的第一个元素对整个列表进行排序.

to be clear i do not want to sort the individual string[] elements. I would like to sort the entire list based on the very first element of the string array.

推荐答案

一个简单的自定义比较器应该可以解决问题.

A simple custom comparator should do the trick.

唯一棘手的事情是确保您没有索引到空数组中

The only tricky thing is making sure that you are not indexing into an empty array:

Collections.sort(allWordList, new Comparator<String[]>() {
    public int compare(String[] o1, String[] o2) {
        if (o1.length == 0) {
            return o2.length == 0 ? 0 : -1;
        }
        if (o2.length == 0) {
            return 1;
        }
        return o2[0].compareTo(o1[0]);
    }
});

这篇关于如何对包含字符串数组的arraylist进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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