A TreeSet or TreeMap that allow duplicates

前端 未结 7 1701
走了就别回头了
走了就别回头了 2021-01-17 23:12

I need a Collection that sorts the element, but does not removes the duplicates.

I have gone for a TreeSet, since TreeSet actu

7条回答
  •  无人共我
    2021-01-18 00:00

    I need all the fundCode with highest fundValue

    If that's the only reason why you want to sort I would recommend not to sort at all. Sorting comes mostly with a complexity of O(n log(n)). Finding the maximum has only a complexity of O(n) and is implemented in a simple iteration over your list:

    List maxFunds = new ArrayList();
    int max = 0;
    for (Fund fund : funds) {
        if (fund.getFundValue() > max) {
            maxFunds.clear();
            max = fund.getFundValue();
    
        }
        if (fund.getFundValue() == max) {
            maxFunds.add(fund);
    
        }
    }
    

    You can avoid that code by using a third level library like Guava. See: How to get max() element from List in Guava

提交回复
热议问题