针对集合中的某个字段对集合中的对象进行排序

class MappSentence {
private String sentence;//匹配到的词
private int length;//匹配到的词的长度
private int mappedLength;//与原短语相同单词的长度
private String standardWord;//映射到的规范词
private double score;

public MappSentence(double score){

this.score=score;

}
public double getScore() {
 return score;
}
public void setScore(double score) {
 this.score = score;
}
public int getLength() {
 return length;
}
public String getSentence() {
 return sentence;
}
public void setSentence(String sentence) {
 this.sentence = sentence;
}
public String getStandardWord() {
 return standardWord;
}
public void setStandardWord(String standardWord) {
 this.standardWord = standardWord;
}
public void setLength(int length) {
 this.length = length;
}
public int getMappedLength() {
 return mappedLength;
}
public void setMappedLength(int mappedLength) {
 this.mappedLength = mappedLength;
}
}

 

class ComparatorScore implements Comparator<MappSentence>{
 @Override
 public int compare(MappSentence m1, MappSentence m2) {
    int flag=-1;
    if(m1.getScore()>m2.getScore()){
     flag=1;
    }
    if(m1.getScore()==m2.getScore()){
     flag=0;
    }
    return flag;
 }
}

 

public class TestSort {

 /**
  * @param args
  */
 public static void main(String[] args)
 {
  List mps=new ArrayList();
  mps.add(new MappSentence(100));
  mps.add(new MappSentence(12));
  mps.add(new MappSentence(31));
  mps.add(new MappSentence(14));
  mps.add(new MappSentence(5));
  mps.add(new MappSentence(16));
  mps.add(new MappSentence(70));
  ComparatorScore cm=new ComparatorScore();
   Collections.sort(mps,cm); 
   for(int i=0;i<mps.size();i++){
    MappSentence mapp=(MappSentence)mps.get(i);
    System.out.println(mapp.getScore());
   }
 }
}

测试结果:

 

5.0
12.0
14.0
16.0
31.0
70.0
100.0
posted @ 2013-02-28 16:22  6小贝  阅读(222)  评论(0编辑  收藏  举报