简体   繁体   English

Java Comparator类对特定对象数组进行排序

[英]Java Comparator class to sort particular object array

I have a float array and a String array. 我有一个浮点数组和一个字符串数组。 each float value match with a specific String. 每个浮点值都与特定的String匹配。 I would like to sort the float array keeping the own string using : 我想使用以下方式对保留自己的字符串的float数组进行排序:

public static <T> void sort(T[] a,Comparator<? super T> c)

Here is the code: 这是代码:

public class ResultVoiceObject
{

     private  String frase;
     private float ranking;
     public ResultVoiceObject(String f, float r) 
       {
        this.frase=f;
        this.ranking= r;
       }  
     }
     public class VoiceRecognitionDemo extends Activity
     {

       // Populate the wordsList with the String values the recognition engine thought it heard
        ArrayList<String> matches = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);          
        //il Ranking
        float[] score= data.getFloatArrayExtra(RecognizerIntent.EXTRA_CONFIDENCE_SCORES);

        ResultVoiceObject[] risultati= new ResultVoiceObject[score.length];
        for (i=0; i<risultati.length;i++)
        {       
            risultati[i]=new ResultVoiceObject(matches.get(i), score[i]);       
        }          
        ResultVoiceObject[] risultatiDaOrdinare= risultati;  // risultati contais ResultVoiceObject elements
                    /*sorting*/
        }

How can I sort by ranking and keeping the own String? 如何排序并保留自己的字符串?

Thanks a lot. 非常感谢。

ResultVoiceObject[] objects = ...
Arrays.sort(objects, new Comparator<ResultVoiceObject>() {

    @Override
    public int compare(ResultVoiceObject arg0, ResultVoiceObject arg1) {
        return Float.compare(arg0.getRanking(), arg1.getRanking());
    }

});

Assuming you have a getRanking() accessor for the private field ranking . 假设您有一个用于私有字段rankinggetRanking()访问器。

public class ResultComparator implements Comparator<ResultVoiceObject> {
  public int compare(ResultVoiceObject r1, ResultVoiceObject r2) {
    float f1 = r1.getRanking();
    float f2 = r2.getRanking();
    if(f1 > f2) return 1;
    else if(f1 < f2) return -1;
    return 0;
  }

}

Arrays.sort(resultsArray, new ResultComparator());

You need to implement the Comparator interface. 您需要实现Comparator接口。 You can create multiple sort sequences while using Comparator . 您可以在使用Comparator同时创建多个排序序列。

Suppose you want to sort your array according to your ranking, then create a separate class which implements Comparator 假设您要根据排名对数组进行排序,然后创建一个单独的类来实现Comparator

public Class RankingSorter implements Comparator<ResultVoiceObject> {
   public int compare(ResultVoiceObject one, ResultVoiceObject another){
       return (int)(one.getRanking() - another.getRanking());
   }
}

Then in the new class that you want to sort your array, You create the object of the comparator and pass it to collection 然后在要对数组进行排序的新类中,创建comparator的对象并将其传递给集合

RankingSorter rs = new RankingSorter();
Collections.sort(yourArray, rs);

This is the overloaded version of sort method which takes the comparator . 这是采用comparatorsort方法的重载版本。

I had written a full tutorial regarding this a while ago http://www.dreamincode.net/forums/topic/174322-the-comparable-and-comparator-interface-part-ii/ 不久前,我已经写了一个完整的教程,有关此信息http://www.dreamincode.net/forums/topic/174322-the-comparable-and-comparator-interface-part-ii/

Here is the ResultVoicObject class 这是ResultVoicObject类

package com.compare;

public class ResultVoiceObject {

private String frase;
private float ranking;

public ResultVoiceObject(String f, float r) {
    this.frase = f;
    this.ranking = r;
}

public String getFrase() {
    return frase;
}

public void setFrase(String frase) {
    this.frase = frase;
}

public float getRanking() {
    return ranking;
}

public void setRanking(float ranking) {
    this.ranking = ranking;
}

@Override
public String toString() {
    return "ResultVoiceObject [frase=" + frase + ", ranking=" + ranking
            + "]";
}

}

Implement the Comparator interface as follows, you need to implement compare method 如下实现Comparator接口,您需要实现compare方法

 package com.compare;

 import java.util.Comparator;

  public class RankingSort implements Comparator<ResultVoiceObject> {

public int compare(ResultVoiceObject one, ResultVoiceObject another){
    return (int) (one.getRanking() - another.getRanking());
}
  }

You can test it as below. 您可以如下进行测试。

 package com.compare;

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

 public class RankingSorterTest{

public static void main(String [] args){

    ArrayList<ResultVoiceObject> list = new ArrayList<ResultVoiceObject>();
    list.add(new ResultVoiceObject("one", 1));
    list.add(new ResultVoiceObject("five", 5));
    list.add(new ResultVoiceObject("three", 3));

    Collections.sort(list,new RankingSort());
    System.out.println(list);

}
  }

If you want to create a sorting sequence using frase, then you just need to create a new comparator class for it and sort just as I have sorted above 如果要使用frase创建排序序列,则只需为其创建一个新的comparator类并按照我上面的排序进行排序

Hope this helps... took a lot of efforts from me also :D :D 希望这会有所帮助...我也付出了很多努力:D:D

I solved merging both answare: 我解决了合并两个软件:

public class VoiceRecognitionDemo extends Activity implements Comparator<ResultVoiceObject {

protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
        ...
        ResultVoiceObject[] risultati= ...;     
        Arrays.sort(risultati, new Comparator<ResultVoiceObject>() {
            @Override
            public int compare(ResultVoiceObject arg0, ResultVoiceObject arg1) {
                return Float.compare(arg0.getRanking(), arg1.getRanking());
            }
        });  

    }


public int compare(ResultVoiceObject lhs, ResultVoiceObject rhs) {
    // TODO Auto-generated method stub
    return 0;
}

} }

Where: 哪里:

 public class ResultVoiceObject
 {

 private  String frase;
 private float ranking;
 public ResultVoiceObject(String f, float r) 
   {
    this.frase=f;
    this.ranking= r;
   }  
 }

Another way is: 另一种方法是:

ADD

import java.util.Arrays; 导入java.util.Arrays;

import java.util.Comparator; 导入java.util.Comparator;

REMOVE: implements Comparator and the compare methos out onActivityResult 删除:实现Comparator和onActivityResult上的比较方法

Thanks stackoverflow comunity! 谢谢stackoverflow社区!

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

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