Java按数字和字母顺序对带有自定义字段的ArrayList进行排序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18312060/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java sort ArrayList with custom fields by number and alphabetically
提问by haind
public class Product implements Serializable{
private String id;
private String name;
private double price ;
private int quantity;
public Product(String id, String name, double price, int quantity) {
this.id = id;
this.name = name;
this.price = price;
this.quantity = quantity;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
@Override
public String toString() {
return "Product{" + "id=" + id + ", name=" + name + ", price=" + price + ", quantity=" + quantity + '}';
}
I want to sort ArrayList<Product>
by price and name. I search Google for a long time but I cann't solve it. Whether it can have problem with Serializable
我想ArrayList<Product>
按价格和名称排序。我在谷歌上搜索了很长时间,但我无法解决。Serializable是否会出现问题
采纳答案by Prasad Kharkar
You need to implement Comparable
or Comparator
interface for your purpose. sorting user defined objects with Comparatorand sorting user defined objects with comparable
您需要为您的目的实现Comparable
或Comparator
接口。使用 Comparator对用户定义的对象进行排序并使用可比较的对用户定义的对象进行排序
You can learn the difference between these two by reading these tutorials
您可以通过阅读这些教程来了解这两者之间的区别
Consider you want your products to be sorted using its price then make your Product
implement Comparable
as follows
考虑您希望使用其价格对您的产品进行排序,然后按如下方式制作您的Product
工具Comparable
public class Product implements Comparable<Product>{
public int compareTo(Product other){
// your logic here
}
}
But hold on... now that we have already implemented Comparable
interface to sort the objects using its price, how can we sort them using another sort sequence? We only have one compareTo()
method and we can't write separate sort sequence in the same class. Here comes the role of Comparator
. With Comparator
, you can define multiple sort sequences.
但是等等......现在我们已经实现Comparable
了使用价格对对象进行排序的接口,我们如何使用另一个排序序列对它们进行排序?我们只有一种compareTo()
方法,不能在同一个类中编写单独的排序序列。的作用来了Comparator
。使用Comparator
,您可以定义多个排序序列。
Suppose we want to sort using its price, then:
假设我们想使用它的价格进行排序,那么:
public class PriceSorter implements Comparator<Product>{
public int compare(Product one, Product another){
int returnVal = 0;
if(one.getPrice() < another.getPrice()){
returnVal = -1;
}else if(one.getPrice() > another.getPrice()){
returnVal = 1;
}else if(one.getPrice() == another.getPrice()){
returnVal = 0;
}
return returnVal;
}
}
and you want another sort sequence, now for its name, then:
你想要另一个排序序列,现在是它的名字,然后:
public class NameSorter implements Comparator<Product>{
public int compare(Product one, Product another){
return one.getName().compareTo(another.getName());
}
}
Now, when you want to sort using price, then
现在,当您想使用价格进行排序时,那么
Collections.sort(yourList,new PriceSorter());
If you want to sort using name, then
如果你想使用名称排序,那么
Collections.sort(yourList, new NameSorter());
The second argument takes the Comparator
instance which makes the sort method know what logic to follow while sorting objects
第二个参数采用Comparator
使 sort 方法知道在对对象进行排序时遵循什么逻辑的实例
回答by Matti Lyra
You need to implement the Comparable
interface. The interface requires you to add a function called compareTo(Product other)
within which you write the code that checks the custom fields you want the objects to be compared by.
您需要实现该Comparable
接口。该接口要求您添加一个被调用的函数,您可以在该函数中compareTo(Product other)
编写代码来检查您希望比较对象的自定义字段。
Alternatively you can do what @Prasad Kharkar suggested and write a Comaparator
that essentially does the same thing.
或者,您可以按照@Prasad Kharkar 的建议进行操作,然后编写一个Comaparator
本质上执行相同操作的方法。
http://docs.oracle.com/javase/7/docs/api/java/lang/Comparable.html
http://docs.oracle.com/javase/7/docs/api/java/lang/Comparable.html
http://www.mkyong.com/java/java-object-sorting-example-comparable-and-comparator/
http://www.mkyong.com/java/java-object-sorting-example-comparable-and-comparator/
回答by Srinath Ganesh
As far as I know , you dont have such methods , what you can do is ; extend a subclass of Collection and add methods to sort (search or techniques like bubble sort,and more)
据我所知,你没有这样的方法,你能做的就是;扩展 Collection 的子类并添加排序方法(搜索或冒泡排序等技术等)
If you have facility for a database (more overhead) *you could put it in there and use order by *if you are using JPA , just dump your list into a entity class
如果你有一个数据库设施(更多的开销)*你可以把它放在那里并使用 order by *如果你使用 JPA ,只需将你的列表转储到实体类中
回答by Bohemian
Use a Comparator<Product>
, here implemented anonymously (suitable for java 7 and earlier):
使用Comparator<Product>
, 此处匿名实现(适用于 java 7 及更早版本):
List<Product> list;
Collections.sort(list, new Comparator<Product>() {
public int compare(Product a, Product b) {
if (a.getPrice() == b.getPrice())
return a.getName().compareTo(b.getName());
return a.getPrice() > b.getPrice() ? 1 : a.getPrice() < b.getPrice() ? -1 : 0
}
});
Java 8 has a much cleaner way of achieving the above:
Java 8 有一种更简洁的方式来实现上述目标:
Collections.sort(list, Comparator.comparing(Product::getPrice).thenComparing(Product::getName));
If this defines the "natural order" of your products, consider making Product
implement Comparable<Product>
and implement it in the compareTo()
method of Product
.
如果这定义了您产品的“自然顺序”,请考虑制定Product
实施Comparable<Product>
并以 的compareTo()
方法实施Product
。
回答by Kevin Bowersox
Have the Product
class implement the Comparable
interface.
让Product
类实现Comparable
接口。
public class Product implements Serializable, Comparable<Product> {
//Ommitted constructors, fields and accessors
//This is an ascending sort order
@Override
public int compareTo(Product o) {
int result = this.name.compareToIgnoreCase(o.name);
if(result != 0){
return result;
}else{
return new Double(this.price).compareTo(new Double(o.price));
}
}
}
Then sorting is as easy as pass the List
to Collections.sort()
:
然后排序就像传递List
给一样简单Collections.sort()
:
public static void main(String[] args) {
Product p1 = new Product("p1", "shoes", 30.33, 20);
Product p2 = new Product("p2", "shoes", 20.30, 20);
Product p3 = new Product("p3", "shoes", 50.33, 20);
Product p4 = new Product("p4", "socks", 10.50, 20);
Product p5 = new Product("p5", "socks", 5.40, 20);
Product p6 = new Product("p6", "socks", 2.34, 20);
List<Product> products = Arrays.asList(p1,p2,p3,p4,p5,p6);
System.out.println("Unsorted");
for(Product product:products){
System.out.println("Product: " + product.name + " Price: " + product.price);
}
Collections.sort(products);
System.out.println("sorted");
for(Product product:products){
System.out.println("Product: " + product.name + " Price: " + product.price);
}
}
Here is the full sourcefor Product
that implements Comparable
with a sort example in the main
method:
下面是完整的源用于Product
实现Comparable
与在一种示例main
方法:
import java.io.Serializable;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class Product implements Serializable, Comparable<Product> {
private String id;
private String name;
private double price;
private int quantity;
public Product(String id, String name, double price, int quantity) {
this.id = id;
this.name = name;
this.price = price;
this.quantity = quantity;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
@Override
public String toString() {
return "Product{" + "id=" + id + ", name=" + name + ", price=" + price
+ ", quantity=" + quantity + '}';
}
@Override
public int compareTo(Product o) {
int result = this.name.compareToIgnoreCase(o.name);
if(result != 0){
return result;
}else{
return new Double(this.price).compareTo(new Double(o.price));
}
}
public static void main(String[] args) {
Product p1 = new Product("p1", "shoes", 30.33, 20);
Product p2 = new Product("p2", "shoes", 20.30, 20);
Product p3 = new Product("p3", "shoes", 50.33, 20);
Product p4 = new Product("p4", "socks", 10.50, 20);
Product p5 = new Product("p5", "socks", 5.40, 20);
Product p6 = new Product("p6", "socks", 2.34, 20);
List<Product> products = Arrays.asList(p1,p2,p3,p4,p5,p6);
System.out.println("Unsorted");
for(Product product:products){
System.out.println("Product: " + product.name + " Price: " + product.price);
}
Collections.sort(products);
System.out.println("sorted");
for(Product product:products){
System.out.println("Product: " + product.name + " Price: " + product.price);
}
}
}