A TreeSet or TreeMap that allow duplicates

前端 未结 7 1695
走了就别回头了
走了就别回头了 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:03

    Instead of the TreeSet we can use List and implement the Comparable interface.

    public class Fund implements Comparable {
    
        String fundCode;
        int fundValue;
    
        public Fund(String fundCode, int fundValue) {
            super();
            this.fundCode = fundCode;
            this.fundValue = fundValue;
        }
    
        public String getFundCode() {
            return fundCode;
        }
    
        public void setFundCode(String fundCode) {
            this.fundCode = fundCode;
        }
    
        public int getFundValue() {
            return fundValue;
        }
    
        public void setFundValue(int fundValue) {
            this.fundValue = fundValue;
        }
    
        public int compareTo(Fund compareFund) {
    
            int compare = ((Fund) compareFund).getFundValue();
            return compare - this.fundValue;
        }
    
        public static void main(String args[]){
    
            List funds = new ArrayList();
    
            Fund fund1 = new Fund("a",100);
            Fund fund2 = new Fund("b",20);
            Fund fund3 = new Fund("c",70);
            Fund fund4 = new Fund("a",100);
            funds.add(fund1);
            funds.add(fund2);
            funds.add(fund3);
            funds.add(fund4);
    
            Collections.sort(funds);
    
            for(Fund fund : funds){
                System.out.println("Fund code: " + fund.getFundCode() +  "  Fund value : " + fund.getFundValue());
            }
        }
    }
    

提交回复
热议问题