Sort the object list based on different data members in Java
•
Java
I have this course:
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 the list according to the name, location, temperature and humidity entered by the user Edit: the user specifies which data member must be sorted What is the easiest way? thank you.
Solution
Java has a called collections The static function of sort (list, comparator), which sorts a (general) object list given a custom comparator, and determines which one is sorted before the other given two objects of the same type
Your task is to write a function that creates a comparator that sorts objects according to parameters and user specified sorting 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 + "'");
}
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码
