java实现基金净值排序
时间: 2023-08-09 11:06:15 浏览: 58
要实现基金净值排序,可以按照以下步骤进行:
1. 定义基金类,包括基金代码、基金名称、基金净值等属性。
2. 创建基金对象,并将基金对象存储到集合中。
3. 定义一个排序方法,使用 Collections.sort() 方法对基金集合进行排序。
4. 在排序方法中实现 Comparator 接口,重写 compare() 方法,根据基金净值进行排序。
下面是一个示例代码:
```java
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class FundSorter {
public static void main(String[] args) {
List<Fund> funds = new ArrayList<Fund>();
funds.add(new Fund("001", "基金1", 1.5));
funds.add(new Fund("002", "基金2", 2.0));
funds.add(new Fund("003", "基金3", 1.8));
funds.add(new Fund("004", "基金4", 1.2));
funds.add(new Fund("005", "基金5", 2.5));
Collections.sort(funds, new Comparator<Fund>() {
public int compare(Fund f1, Fund f2) {
return Double.compare(f2.getNetValue(), f1.getNetValue());
}
});
for (Fund fund : funds) {
System.out.println(fund.getCode() + " " + fund.getName() + " " + fund.getNetValue());
}
}
}
class Fund {
private String code;
private String name;
private double netValue;
public Fund(String code, String name, double netValue) {
this.code = code;
this.name = name;
this.netValue = netValue;
}
public String getCode() {
return code;
}
public String getName() {
return name;
}
public double getNetValue() {
return netValue;
}
}
```
输出结果为:
```
005 基金5 2.5
002 基金2 2.0
003 基金3 1.8
001 基金1 1.5
004 基金4 1.2
```
这里使用了 Collections.sort() 方法对基金集合进行排序,传入了一个 Comparator 对象作为参数,重写了 compare() 方法,根据基金净值进行排序。最后输出排序后的基金信息。