简体   繁体   English

如何根据一个数组的值对两个数组排序

[英]How to sort two arrays according to one array's values

public static void getSort(short[] time, String[] champs){
    System.out.println("Time     Champs\n");
    for(int a= 0; a < time.length; a++){
        char Fletter=champs[a].charAt(0);
        if('B' == Fletter){
            Arrays.sort(champs);
            System.out.println(time[a] + "     " + champs[a]);
        }
    }
    for(int a= 0; a < time.length; a++){
        char Fletter=champs[a].charAt(0);
        if('C' == Fletter){
            Arrays.sort(champs);
            System.out.println(time[a] + "     " + champs[a]);
        }
    }
}

Hi guys, I'm in need for some advice and help on this function. 大家好,我需要有关此功能的一些建议和帮助。 What I am trying to do is output and display what is inside the arrays time and champs. 我想做的是输出并显示数组时间和冠军中的内容。

What my desire output is to have is: 我期望的输出是:

Time----Champs

2001 Banana   

2004 Banana

2000 Boat

2003 Boat

2011 Carrot

2013 Carrot

2002 Cucumber

Where the time and champs are displayed correctly being displayed alphabetically But when I use Arrays.sort(champs); 时间和冠军的正确显示位置按字母顺序显示,但是当我使用Arrays.sort(champs);

My output is: 我的输出是:

Time----Champs

2004  Banana

2005  Banana

2006  Boat

2007  Boat

2008  Carrot

2009  Carrot

2010  Cucumber

The output of champs is displayed correctly but the years are listed down going down by 1. 冠军的输出正确显示,但年份向下列出了1。

And without the Arrays.sort(champs) my output is: 没有Arrays.sort(champs)我的输出是:

Time----Champs

2000 Boat

2001 Banana  

2003 Boat

2004 Banana

2002 Cucumber

2011 Carrot

2013 Carrot

Which as you can see the time is correct with the champs but not sorted alphabetically. 如您所见,时间对于冠军是正确的,但不是按字母顺序排序的。

I think your issue is that you're not re-ordering the 'time' with the 'champs'. 我认为您的问题是您没有用“冠军”重新排列“时间”。 From your example, it appears as though 'time' is just years in increasing order, and champs is whoever the champion team was for that year. 从您的示例中可以看出,“时间”似乎只是按照递增顺序排列的年份,而冠军就是那一年的冠军队。 When you sort the Champs into alphabetical order, they're out of sync with the time. 当您将冠军按字母顺序排序时,它们与时间不同步。

To solve this, you need to pair Time with Champs so that if you sort by one of the values, the other moves with it. 要解决此问题,您需要将“时间”与“冠军”配对,以便如果按其中一个值排序,则另一个将随之移动。

Start with an internal class like this: 从这样的内部类开始:

public static class Tuple implements Comparable<Tuple>{
    public short time;
    public String champ;

    public Tuple(short time, String champ) {
        this.time = time;
        this.champ = champ;
    }

    public int compareTo(Tuple other) {
        return this.champ.compareTo(other.champ);
    }
}

Then, where change your current method to make an array of Tuples: 然后,在其中更改当前方法以创建元组数组:

public static void getSort(short[] time, String[] champs){
   // assuming time.length & champ.length are the same
   Tuple[] timechamps = new Tuple[time.length];
   for (int a = 0; a < time.length; a++) {
     timechamps[a] = new Tuple(time[a], champs[a]);
   }

because we've made the new tuple implement Comparable, we can simply sort it. 因为我们使新的元组实现可比较,所以我们可以对其进行排序。 The compareTo method of the tuple sorts in alphabetical order properly. 元组的compareTo方法按字母顺序正确排序。

   Arrays.sort(timechamps);

Then you can print out the results 然后您可以打印出结果

   for (Tuple t : timechamps) {
     System.out.println(t.time+"\t"+t.champ);
   }
 }

Would you like to have a look here http://www.mkyong.com/java/how-to-sort-a-map-in-java/ 您想在这里看看吗http://www.mkyong.com/java/how-to-sort-a-map-in-java/

Here Key -----> champs Values --> time 这里键----->冠军值->时间

I think you want to short your champs and time should be maintained with corresponding values. 我认为您想缩短冠军的时间,应该用相应的值保持时间。 Hope its helpful to you. 希望它对您有所帮助。

It is better to create a Class and implement Comparable method 最好创建一个Class并实现Comparable方法

public class TimeChamp implements Comparable<TimeChamp>{

private short time;
private String champs;

public short getTime() {
    return time;
}

public void setTime(short time) {
    this.time = time;
}

public String getChamps() {
    return champs;
}

public void setChamps(String champs) {
    this.champs = champs;
}

@Override
public int compareTo(TimeChamp o) {
    if(getChamps().compareTo(o.getChamps())==0)
    {
        if(getTime()<o.getTime())
            return -1;
        else
            return 1;
    }
    else
        return getChamps().compareTo(o.getChamps());
}
}

Then you can create the function which will sort in your class like this 然后,您可以创建将在您的类中排序的函数,如下所示

public void getSort(TimeChamp[] timeChamp)
{
    Arrays.sort(timeChamp);
    for(int i=0;i<timeChamp.length;i++)
    {   
        System.out.print(timeChamp[i].getTime());
        System.out.print("            ");
        System.out.println(timeChamp[i].getChamps());
    }
}

EDIT : Writing a more descriptive answer which constructs the data sets and calls the sort method 编辑:编写一个更具描述性的答案,该答案构造数据集并调用sort方法

import java.util.Arrays;


public class MainExample {

/**
 * @param args
 */
public static void main(String[] args) {
            //Construct data sets
    TimeChamp [] timeChampArray = new TimeChamp[3];
    TimeChamp timeChamp = new TimeChamp();
    timeChamp.setChamps("Boat");
    timeChamp.setTime((short)2001);
    timeChampArray[0]=timeChamp;
    timeChamp= new TimeChamp();
    timeChamp.setChamps("Banana");
    timeChamp.setTime((short)2000);
    timeChampArray[1]=timeChamp;
    timeChamp= new TimeChamp();
    timeChamp.setChamps("Banana");
    timeChamp.setTime((short)2001);
    timeChampArray[2]=timeChamp;
            //Call the sort method
    new MainExample().getSort(timeChampArray);
}
//the sorting method
public void getSort(TimeChamp[] timeChamp)
{
    Arrays.sort(timeChamp);
    for(int i=0;i<timeChamp.length;i++)
    {   
        System.out.print(timeChamp[i].getTime());
        System.out.print("            ");
        System.out.println(timeChamp[i].getChamps());
    }
}

} }

I also had a go. 我也去了。 This is a fully functional, self-contained solution. 这是一个功能齐全的独立解决方案。

import java.util.Arrays;

public class TimeAndChampSorter {

    public static void main(String[] args) {
        // prepare input
        short[] time = { 2000, 2001, 2003, 2004, 2002, 2011, 2013 };
        String[] champs = { "Boat", "Banana", "Boat", "Banana", "Cucumber",
                "Carrot", "Carrot" };
        printSorted(time, champs);
    }

    public static void printSorted(short[] time, String[] champs) {
        // check arguments are of equal length
        if (time.length != champs.length) {
            throw new IllegalArgumentException(
                    "arrays time and champs must have equal length");
        }
        Tuple[] tuples = createTuples(time, champs);
        Arrays.sort(tuples);
        printTuples(tuples);
    }

    private static Tuple[] createTuples(short[] time, String[] champs) {
        // create empty array of Tuples with correct length
        Tuple[] tuples = new Tuple[champs.length];
        // fill the tuples array
        for (int i = 0; i < champs.length; i++) {
            tuples[i] = new Tuple(time[i], champs[i]);
        }
        return tuples;
    }

    private static void printTuples(Tuple[] tuples) {
        System.out.println("Time     Champs\n");
        for (Tuple tuple : tuples) {
            System.out.println(tuple);
        }
    }

    // static class to avoid having to create an instance of TimeAndChampSorter
    static class Tuple implements Comparable<Tuple> {
        short time;
        String champ;

        Tuple(short time, String champ) {
            // make sure champ is not null to avoid having to test for nulls in
            // compareTo
            if (champ == null) {
                throw new IllegalArgumentException("champ can not be null");
            }
            this.time = time;
            this.champ = champ;
        }

        // method of Comparable interface determines the ordering
        @Override
        public int compareTo(Tuple other) {
            return this.champ.compareTo(other.champ);
        }

        @Override
        public String toString() {
            return time + "     " + champ;
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM