gpt4 book ai didi

java - 在java中对二维数组进行排序(对所有字母进行排序)

转载 作者:行者123 更新时间:2023-11-29 05:42:51 26 4
gpt4 key购买 nike

我想对以下二维数组进行排序:

String[][] rows = {
{"M","O","N","K","E","Y"},
{"D","O","N","K","E","Y"},
{"M","A","K","E"},
{"M","U","C","K","Y"},
{"C","O","O","K","Y"},
};

我希望得到以下结果:

A C C D E E E K K K K K M M M N N O O O O U Y Y Y Y

但是我不知道该怎么做!!我找不到任何关于 2D 数组排序的好例子。

如您所见,我不想按列或行排序,但我只想对数组中的所有字符进行排序。通过这种方式,我可以计算每个字符在二维数组中的位置。

如果您知道如何计算二维数组中每个字符的数量,那对我来说也是一个很好的解决方案。

最佳答案

这将使用 Collections.sort 将二维数组排序为 List 对象。

import java.util.List;
import java.util.ArrayList;
import java.util.Collections;

public class Test {
public static void main(String[] args) {
String[][] rows = {
{"M","O","N","K","E","Y"},
{"D","O","N","K","E","Y"},
{"M","A","K","E"},
{"M","U","C","K","Y"},
{"C","O","O","K","Y"},
};

List<String> list = new ArrayList<String>();

// Add all strings to list.
for (String[] row : rows) {
for (String s : row) {
list.add(s);
}
}

Collections.sort(list); // Sort the list.
}
}

您可以使用以下方法将列表转换为基本数组:

String[] arr = list.toArray(new String[list.size()]);

要计算数组中的每个字符,请查看 jlordo's回答。

关于java - 在java中对二维数组进行排序(对所有字母进行排序),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16885043/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com