java 在java中对字符串的二维数组进行排序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5064027/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
sorting 2D array of String in java
提问by Julio Diaz
I know that this question might have been asked before, but I was not able to find a fit answer. So say I have this array:
我知道之前可能有人问过这个问题,但我找不到合适的答案。所以说我有这个数组:
String [][] theArray = {{"james", "30.0"},{"joyce", "35.0"},{"frank", "3.0"}, {"zach", "34.0"}}
Is there a way to descendingly sort this array by the second element of each sub-element. So I would get something like this.
有没有办法按每个子元素的第二个元素对这个数组进行降序排序。所以我会得到这样的东西。
theArray = {{"joyce", "35.0"},{"zach", "34.0"},{"james", "30.0"}, {"frank", "3.0"}}
Thanks guys
多谢你们
采纳答案by JB Nizet
You must use the Arrays.sort() method. This method takes a Comparatoras argument. The sort method delegates to the comparator to determine if one element of the array must be considered bigger, smaller or equal to another element. Since every element of the outer array is an array, the comparator will have to compare arrays (of Strings).
您必须使用Arrays.sort() 方法。此方法将Comparator作为参数。sort 方法委托比较器来确定数组的一个元素是否必须被视为大于、小于或等于另一个元素。由于外部数组的每个元素都是一个数组,因此比较器必须比较(字符串)数组。
The arrays must be compared based on the value of their second element. This second element is a String which in fact represents a double number. So you'll have to transorm the strings into numbers, else the order will be lexicographical (20 come before 3) rather than numerical.
必须根据数组的第二个元素的值来比较数组。第二个元素是一个字符串,它实际上表示一个双数。因此,您必须将字符串转换为数字,否则顺序将是字典顺序(20 在 3 之前)而不是数字。
The comparator could thus look like this :
因此,比较器可能如下所示:
public class StrinArrayComparator implements Comparator<String[]> {
@Override
public int compare(String[] array1, String[] array2) {
// get the second element of each array, andtransform it into a Double
Double d1 = Double.valueOf(array1.[1]);
Double d2 = Double.valueOf(array2.[1]);
// since you want a descending order, you need to negate the
// comparison of the double
return -d1.compareTo(d2);
// or : return d2.compareTo(d1);
}
}
回答by Sean Patrick Floyd
Use Arrays.sort(arr, comparator)
with a custom comparator:
使用Arrays.sort(arr, comparator)
带有自定义比较:
Arrays.sort(theArray, new Comparator<String[]>(){
@Override
public int compare(final String[] first, final String[] second){
// here you should usually check that first and second
// a) are not null and b) have at least two items
// updated after comments: comparing Double, not Strings
// makes more sense, thanks Bart Kiers
return Double.valueOf(second[1]).compareTo(
Double.valueOf(first[1])
);
}
});
System.out.println(Arrays.deepToString(theArray));
Output:
输出:
[[joyce, 35.0], [zach, 34.0], [james, 30.0], [frank, 23.0]]
[[乔伊斯,35.0],[扎克,34.0],[詹姆斯,30.0],[弗兰克,23.0]]
Beware:
谨防:
you will be sorting the array you passed in, Arrays.sort()
will not return a new array (in fact it returns void). If you want a sorted copy, do this:
您将对传入的数组进行排序,Arrays.sort()
不会返回新数组(实际上它返回void)。如果您想要一个排序的副本,请执行以下操作:
String[][] theCopy = Arrays.copyOf(theArray, theArray.length);
And perform the sorting on theCopy
, not theArray
.
并在 上执行排序theCopy
,而不是theArray
。
回答by trashgod
If you want to move away from arrays, here's a variation that uses List<Record>
and a RecordComparator
that implements Comparator<Record>
.
如果你想远离数组,这里有一个使用List<Record>
和 a RecordComparator
that的变体implements Comparator<Record>
。
Console:
安慰:
joyce 35.0 zach 34.0 james 30.0 frank 23.0
Code:
代码:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
/** @see http://stackoverflow.com/questions/5064027 */
public class ComparatorTest {
public static void main(String[] args) {
List<Record> list = new ArrayList<Record>(Arrays.asList(
new Record("james", "30.0"),
new Record("joyce", "35.0"),
new Record("frank", "23.0"),
new Record("zach", "34.0")));
print(list, Sort.DESCENDING, Field.D);
}
private static void print(List<Record> list, Sort s, Field f) {
RecordComparator rc = new RecordComparator(s, f);
Collections.sort(list, rc);
for (Record r : list) {
System.out.println(r);
}
}
}
class Record {
private String s;
private Double d;
public Record(String name, String number) {
this.s = name;
this.d = Double.valueOf(number);
}
@Override
public String toString() {
return s + " " + d;
}
public int compareTo(Field field, Record record) {
switch (field) {
case S: return this.s.compareTo(record.s);
case D: return this.d.compareTo(record.d);
default: throw new IllegalArgumentException(
"Unable to sort Records by " + field.getType());
}
}
}
enum Sort { ASCENDING, DESCENDING; }
enum Field {
S(String.class), D(Double.class);
private Class type;
Field(Class<? extends Comparable> type) {
this.type = type;
}
public Class getType() {
return type;
}
}
class RecordComparator implements Comparator<Record> {
private Field field;
private Sort sort;
public RecordComparator(Sort sort, Field field) {
this.sort = sort;
this.field = field;
}
@Override
public final int compare(Record a, Record b) {
int result = a.compareTo(field, b);
if (sort == Sort.ASCENDING) return result;
else return -result;
}
}
回答by Joachim Sauer
You seem to be living in object denial. Those inner arrays look a lot like information about a Person (with the name and some value, maybe a score).
你似乎生活在拒绝对象中。那些内部数组看起来很像关于一个人的信息(有名字和一些值,可能是一个分数)。
What you'd want to do is to write a custom class to hold that information:
您想要做的是编写一个自定义类来保存该信息:
public class Person {
private final String name;
private final double score;
public Person(final String name, final double score) {
this.name=name;
this.score=score;
}
public String getName() {
return name;
}
public double getScore() {
return score;
}
}
Then, when you want to sort them, you simply implement a Comparator<Person>
that specifies how you want them sorted:
然后,当你想对它们进行排序时,你只需实现一个Comparator<Person>
指定你希望它们如何排序的:
public PersonScoreComparator implements Comparator<Person> {
public int compare(Person p1, Person p2) {
return Double.compare(p1.getScore(), p2.getScore());
}
}
Alternatively, you could have the Person
class itself implement Comparable<Person>
by adding this method:
或者,您可以通过添加此方法Person
来实现类本身Comparable<Person>
:
public int compareTo(Person other) {
return Double.compare(getScore(), other.getScore());
}
回答by Umesh K
-Create list out of this array using Arrays.toList() -Design comparator using java.lang.comparator and write logic for sorting every even elements
- 使用 Arrays.toList() 从该数组中创建列表 - 使用 java.lang.comparator 设计比较器并编写用于对每个偶数元素进行排序的逻辑
回答by jmg
There are several sort methods in java.util.Arrays
. Two of them take custom Comparator
s. Simply provide a comparator comparing the second element of the inner arrays.
中有几种排序方法java.util.Arrays
。其中两个采取 custom Comparator
s。只需提供一个比较器来比较内部数组的第二个元素。
回答by prakash
public static void main(String[] args) {
公共静态无效主(字符串 [] args){
String Name[][]={{"prakash","kumar"},{"raj","kappor"},{"vinod","bhart"}};
String str[]=new String[2];
for(int j=0; j<Name.length;j++)
{
for (int i=0 ; i<2; i++)
{
str[i]=Name[j][i];
}
for(int i=0;i<str.length;i++)
{
for(int k=i+1;k<str.length;k++)
{
if(str[i].compareTo(str[k])>0)
{
String temp= str[i];
str[i]=str[k];
str[k]=temp;
}
}
System.out.print(str[i]+ " ");
}
System.out.println();
}
}
}
回答by sorin147
/**
*
* @param array - 2D array required to be arranged by certain column
* @param columnIndex - starts from 0; this will be the main comparator
* @param hasHeaders - true/false; true - ignore the first row. False -
* first row it's also compared and arranged
* @return - the new arranged array
*/
private String[][] arrangeArray(String[][] array, int columnIndex, boolean hasHeaders) {
int headersExists = 0;
if (hasHeaders) {
headersExists = 1;
}
for (int i = headersExists; i < array.length; i++) {
for (int j = headersExists; j < array.length; j++) {
if (array[i][columnIndex].compareTo(array[j][columnIndex]) < 0){
String[] temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
}
return array;
}