排序包含自定义对象的ArrayList。

huangapple go评论71阅读模式
英文:

Sort ArrayList which consist of custom objects

问题

I have created a class called History. The constructor in this class looks like this:

public History(long id, String res, double deposit, double odds, String sport, double ret, String user_name, Date date) {
    this.id = id;
    this.res = res;
    this.deposit = deposit;
    this.odds = odds;
    this.sport = sport;
    this.ret = ret;
    this.user_name = user_name;
    this.date = date;    
}

The class also consists of respective getId() methods, etc.

The objects of the class "History" consist of different value types, e.g., double, String, and Date.

I then have an ArrayList of History objects which contains many of these objects. I want to sort the ArrayList by the highest values of "Double ret," e.g. Is there any way of doing this?

英文:

I have created a class called History. The constructor in this class looks like this:

public History(long id, String res, double deposit, double odds, String sport, double ret, String user_name, Date date) {
		this.id = id;
		this.res = res;
		this.deposit = deposit;
		this.odds = odds;
		this.sport = sport;
		this.ret = ret;
		this.user_name = user_name;
		this.date = date;	
	}

The class also consist of respective getId() methods ect.

The objects of the class "History" consist of different value types e.g. double, String and Date.

I then have an ArrayList of History objects which contains many of these objects. I want to sort the ArrayList by the highest values of "Double ret" e.g. Is there any way of doing this?

答案1

得分: 2

Using java 8 streams Comparator

List<History> sortedUsers = historyList.stream()
  .sorted(Comparator.comparing(History::getRet))
  .collect(Collectors.toList());

Alternatively, you can implement the comparable interface

public class History implements Comparable<History> {
  
  // constructor, getters, and setters
  
  @Override
  public int compareTo(History h) {
    return Double.compare(getRet(), h.getRet());
  }
}
英文:

Using java 8 streams Comparator

List&lt;History&gt; sortedUsers = historyList.stream()
  .sorted(Comparator.comparing(History::getRet))
  .collect(Collectors.toList());

Alternatively you can implement the comparable interface

public class History implements Comparable&lt;History&gt; {
  
  // constructor, getters and setters
 
  @Override
  public int compareTo(History h) {
    return Double.compare(getRet(), h.getRet())
  }
}

huangapple
  • 本文由 发表于 2020年8月11日 16:36:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/63354516.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定