如何在java中使用比较器来比较diff对象的值

时间:2012-02-26 00:09:56

标签: java comparator

  public  void dataAnalytics()
  {
  double sum=0;  
  double i=0;
  double minage=20;
  double maxage=20;

    System.out.println("dataAnalytics for the Rural region");

    for (Record ee :RList)
    {
      sum=sum+Double.valueOf(ee.getIncome());
      i++;

      if (ee.getAge()<20)
          minage=ee.getAge();
      if (ee.getAge()>20)
          maxage=ee.getAge();

    }
    System.out.println("Average income for the Rural region is : $"+sum/i);
    System.out.println("Min age  for the Rural region is : "+minage);
    System.out.println("Max age for the Rural region is : "+maxage);

}

我在java中编写了以下代码,它通过一个arraylist RList并计算所有收入元素的总和,然后取平均值。它的另一个功能是计算最大值和最小值。如何使用java比较器类完成相同的操作?

2 个答案:

答案 0 :(得分:2)

class AgeComparator implements Comparator {

    public int compare( Object o1, Object o2 ){

        int age1 = ((Record)o1).getAge();
        int age2 = ((Record)o2).getAge();

        if ( age1 > age2 ){ return 1; }
        else if ( age1 < age2 ){ return -1; }
        return 0;  
    }

}

public void dataAnalytics(){

    Record[] records = rList.toArray();
    Arrays.sort( records, new AgeComparator() );

    int maxAge = (records[0]).getAge();
    int minAge = (records[ records.length - 1]).getAge();

    System.out.println("Min age  for the Rural region is : " + minAge );
    System.out.println("Max age for the Rural region is : " + maxAge );

}

答案 1 :(得分:0)

public class OrderComparator implements Comparator<Order> { 
    @Override
    public int compare(Order b1, Order b2) {
        int i = b1.getCusType().compareTo(b2.getCusType());
        if(i!=0){
        return Integer.compare(b1.getOrderID(), b2.getOrderID());
        }
        else{
        return i;
        }
    }

如何通过特定词使用比较器进行比较 - 示例 3 类客户:“NEWBIES”、“REGULARS”和 “贵宾”