本文介绍了如何按字母顺序在Java类二维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以说我有一个二维数组:

 的String [] [] =改编{
{鲍勃,一},
{杰克,二},
{亚当,三}
};

我想根据列按字母顺序0排序
所以亚当是第一鲍勃插孔 - 它(或新阵列)看起来像这样:

  {亚当,三}
{鲍勃,一},
{杰克,二},


解决方案

 进口java.util.Arrays中;
进口了java.util.Comparator;
公共类demo_sort {    公共静态无效的主要(字串[] args){        最终的String [] []数据=新的String [] [] {
                新的String [] {鲍勃,一},
                新的String [] {千斤顶,二},
                新的String [] {亚当,三}
                };        Arrays.sort(数据,新的比较<的String []>(){
            @覆盖
            公众诠释比较(最终的String []取值范,最终的String [] ENTRY2){
                最后弦乐时间1 =取值范[0];
                最后弦乐时间2 = ENTRY2 [0];
                返回time1.compareTo(时间2);
            }
        });        对于(最终的String [] S:数据){
            的System.out.println(S [0] ++ S [1]);
        }    }}

输出

亚当3结果
鲍勃·1结果
插孔两个

Lets say i have a two dimensional array:

String [][] arr = {
{"bob","one"},
{"jack","two"},
{"adam","three"}
};

i would like to sort alphabetically according to column 0so adam would be first the bob the jack - and it (or new array) will look like so:

{"adam","three"}
{"bob","one"},
{"jack","two"},
解决方案
import java.util.Arrays;
import java.util.Comparator;


public class demo_sort {

    public static void main(String[] args) {

        final String[][] data = new String[][] {
                new String[] {"bob","one"},
                new String[] {"jack","two"},
                new String[] {"adam","three"}
                };

        Arrays.sort(data, new Comparator<String[]>() {
            @Override
            public int compare(final String[] entry1, final String[] entry2) {
                final String time1 = entry1[0];
                final String time2 = entry2[0];
                return time1.compareTo(time2);
            }
        });

        for (final String[] s : data) {
            System.out.println(s[0] + " " + s[1]);
        }

    }

}

output

adam three
bob one
jack two

这篇关于如何按字母顺序在Java类二维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-02 10:47