根据对象字段的分组对列表进行排序,根据组中的最大值进行排序

时间:2018-02-22 17:43:54

标签: java sorting comparator

我正在尝试根据分组对arraylist进行排序。 假设我有一个货币和现金清单 100美元 75加元 10美元 80欧元, 5美元

我想根据货币降序的最大现金对列表进行排序,因此需要看起来像。 100美元,10美元,5美元,80欧元,75加元。

我写下面的课程来实现同样但没有运气,可以有人帮忙。

import java.math.BigDecimal;
import java.util.Comparator;

public class BO {

    String ccy;
    BigDecimal cash;


public String getCcy() {
    return ccy;
}


public void setCcy(String ccy) {
    this.ccy = ccy;
}


public BigDecimal getCash() {
    return cash;
}


public void setCash(BigDecimal cash) {
    this.cash = cash;
}


@Override
public String toString() {
    return "BO [ccy=" + ccy + ", cash=" + cash + "]";
}
public static final Comparator<BO> CUSTOM_SORTER = new Comparator<BO>() {
    @Override
    public int compare(BO o1, BO o2) {
        return o2.getCash().compareTo(o1.getCash());
    }
};

}

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class BODriver {

public static void main(String[] args) {
BO one = new BO();
one.setCcy("USD");
one.setCash(new BigDecimal(100));
BO two = new BO();
two.setCcy("CAD");
two.setCash(new BigDecimal(50));
BO three = new BO();
three.setCcy("USD");
three.setCash(new BigDecimal(10));
BO four = new BO();
four.setCcy("EUR");
four.setCash(new BigDecimal(70));
BO five = new BO();
five.setCcy("USD");
five.setCash(new BigDecimal(5));

List<BO> boList = new ArrayList<BO>();
boList.add(five);
boList.add(four);
boList.add(three);
boList.add(two);
boList.add(one);

System.out.println("Before sort");
System.out.println(boList);
Collections.sort(boList,BO.CUSTOM);
System.out.println("After sort");
System.out.println(boList);

}

}

3 个答案:

答案 0 :(得分:0)

也许你可以在BO类中添加一个字符串字段来连接ccy +&#34; &#34; + cash.e.g并且您可以使用该字符串字段轻松地对对象进行排序。

答案 1 :(得分:0)

public static final Comparator<BO> CUSTOM_SORTER = new Comparator<BO>() {
    @Override
    public int compare(BO o1, BO o2) {
       if(o2.getCcy().compareTo(o1.getCcy())==0)
         return o2.getCash().compareTo(o1.getCash());
       else
         return o2.getCcy().compareTo(o1.getCcy());
    }
};

试试这个比较器..

答案 2 :(得分:0)

这是一个两步过程。

首先找到每种货币的最大值:

    Map<String, BigDecimal> maxGroup = boList.stream().collect( 
    Collectors.toMap(BO::getCcy, BO::getCash, BigDecimal::max) );

然后按最大现金价值排序,然后按货币排序,最后按每个BO对象的现金价值排序:

    Comparator<BO> comparator = Comparator
    .<BO, BigDecimal>comparing( (bo) -> maxGroup.get( bo.getCcy() ) ).reversed() //first compare by max cash in desc order
    .thenComparing(BO::getCcy) //then by currency
    .thenComparing( Comparator.comparing(BO::getCash).reversed() ); //and finally by cash in desc order

    Collections.sort( boList, comparator);