如何对 2D ArrayList<String> 进行排序通过仅第一个元素 [英] How to Sort 2D ArrayList&lt;String&gt; by Only the First Element

查看:23
本文介绍了如何对 2D ArrayList<String> 进行排序通过仅第一个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为了避免重复声明,我查看了这个 发布,这不是我想要的.
其他所有 2D ArrayList 问题都涉及 doubleint 数字;我的问题是关于 Strings.

To avoid the duplicate claims, I've looked at this post and it isn't exactly what I wanted.
Every other 2D ArrayList question involved double or int numbers; my question is about Strings.

我有一个 2D ArrayList,定义如下:

I have a 2D ArrayList, defined like this:

ArrayList<ArrayList<String>> namesAndNumbers = new ArrayList<ArrayList<String>>();

这个想法是,ArrayLists 的每一行中的第一项包含名称,每行中的其余列包含电话号码(数量未知).因此我想避免将其转换为常规数组.

The idea is that the first item in every row of ArrayLists contains the names, and the rest of the columns in each row contains the phone numbers (unknown amount). Therefore I would like to avoid converting it to a regular array.

假设我已经填充了我的 ArrayList 并且我有这个:

Let's say I've populated my ArrayList and I have this:

{"Mike", "(805) 766-4920"}
{"Emily", "(705) 668-9292", "(705) 555-1060"}
{"James", "(605) 965-2000"}

我希望我的输出是这样的:

{"Emily", "(705) 668-9292", "(705) 555-1060"}    
{"James", "(605) 965-2000"}
{"Mike", "(805) 766-4920"}

我想保留与名称对应的数字,但只需按名称对数组进行排序.

I want to keep the numbers corresponding with the names, but simply sort the array by the name.

我希望有一种内置的函数操作类型,但如果有人为我创建了一个以 2D ArrayList 作为输入的排序数组方法,我会很好.我还没有看到任何明确回答这个问题的问题.我自己也会继续努力想出一个答案.

I'm hoping for a built-in function manipulation type of thing, but I'd be fine if someone created a sorting array method for me with an 2D ArrayList as the input. I haven't seen any question that answers this issue explicitly. I will continue trying to come up with an answer myself as well.

推荐答案

您可以使用 Collections.sort 并提供自定义 Comparator 比较每个列表的第一个元素,即名称:

You can use Collections.sort and provide a custom Comparator where you compare the first element of each list, i.e the name :

List<ArrayList<String>> namesAndNumbers = new ArrayList<ArrayList<String>>();
namesAndNumbers.add(new ArrayList<String>(Arrays.asList("Mike", "(805) 766-4920")));
namesAndNumbers.add(new ArrayList<String>(Arrays.asList("Emily", "(705) 668-9292", "(705) 555-1060")));
namesAndNumbers.add(new ArrayList<String>(Arrays.asList("James", "(605) 965-2000")));
Collections.sort(namesAndNumbers, new Comparator<ArrayList<String>>() {    
        @Override
        public int compare(ArrayList<String> o1, ArrayList<String> o2) {
            return o1.get(0).compareTo(o2.get(0));
        }               
});
System.out.println(namesAndNumbers);

输出:

[[Emily, (705) 668-9292, (705) 555-1060], [James, (605) 965-2000], [Mike, (805) 766-4920]]

这篇关于如何对 2D ArrayList<String> 进行排序通过仅第一个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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