根据Java中不同的数据成员对对象列表进行排序 [英] Sorting a list of objects based on different data members in java

查看:309
本文介绍了根据Java中不同的数据成员对对象列表进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


我上了这个课:


I have this class:

public class Friend {

private String name;
private String location;
private String temp;
private String humidity;

public String getTemp() {
    return temp;
}

public void setTemp(String temp) {
    this.temp = temp;
}

public String getHumidity() {
    return humidity;
}

public void setHumidity(String humidity) {
    this.humidity = humidity;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}


public String getLocation() {
    return location;
}

public void setLocation(String location) {
    this.location = location;
}
}

我想根据用户输入的名称,位置,温度和湿度对列表进行排序.
用户指定必须由哪个数据成员进行排序.
最简单的方法是什么?
谢谢.

I want to sort a List based on name, location, temp and humidity based on user input.
The user specifies by which data member the sorting has to be done.
What is the easiest way to do this?
Thank you.

推荐答案

Java具有称为

Java has a static function called Collections.sort(List, Comparator) which sorts a (generified) List of objects given a custom Comparator which, given two objects of the same type, determines which one is ordered before the other.

您的任务是编写一个创建的函数比较器,根据对象的参数和用户指定的排序顺序对其进行排序.例如:

Your task is to write a function which creates a Comparator which orders the objects based on its arguments and the user specified sort order. For example:

public Comparator<Friend> getComparator(final String sortBy) {
  if ("name".equals(sortBy)) {
    return new Comparator<Friend>() {
      @Override int compare(Friend f1, Friend f2) 
        return f1.getName().compareTo(f2.getName());
      }
    };
  } else if ("location".equals(sortBy)) {
    return new Comparator<Friend>() {
      @Override int compare(Friend f1, Friend f2) 
        return f1.getLocation().compareTo(f2.getLocation());
      }
    };
  } else if ("temp".equals(sortBy)) {
    // ...
  } else {
    throw new IllegalArgumentException("invalid sort field '" + sortBy + "'");
  }
}

这篇关于根据Java中不同的数据成员对对象列表进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆