Как отсортировать ArrayList Java

1

У меня есть этот массивList, который мне нужно сначала сортировать от наибольшего к минимуму по цене обоих предметов, а затем после того, как мне нужно отсортировать его по количеству проданных предметов. Самый простой способ сделать это? благодарю!

 import java.util.*;
 public class salesPerson {

   //salesPerson fields
   private int salespersonID;
   private String salespersonName;
   private String productType;
   private int unitsSold = 0;
   private double unitPrice;

   //Constructor method
   public salesPerson(int salespersonID, String salespersonName, String productType, int unitsSold, double unitPrice)
   {
     this.salespersonID = salespersonID;
     this.salespersonName = salespersonName;
     this.productType = productType;
     this.unitsSold = unitsSold;
     this.unitPrice = unitPrice;
   }


   //Accessor for salesPerson
   public int getSalesPersonID()
   {
       return salespersonID;
    }

   public String getSalesPersonName()
   {
       return salespersonName;
   }

   public String getProductType()
   {
       return productType;
    }

   public int getUnitsSold()
   {
       return unitsSold;
    }

   public double getUnitPrice()
   {
       return unitPrice;
    }

   public double getTotalSold()
   {
        return unitsSold * unitPrice;
    }

   //Mutoators for salesPerson
   public void setSalesPersonID(int salespersonID)
   {
       this.salespersonID = salespersonID;
   }

   public void setSalesPersonName(String salespersonName)
   {
       this.salespersonName = salespersonName;
    }

   public void setProductType(String productType)
   {
       this.productType = productType;
    }

   public void setUnitsSold(int unitsSold)
   {
       this.unitsSold += unitsSold;
    }

   public void setUnitProce(double unitPrice)
   {
       this.unitPrice = unitPrice;
    }

    public static void main(String[] args)
    {
        ArrayList<salesPerson> salesPeople = new ArrayList<salesPerson>();
        Scanner userInput = new Scanner(System.in);
        boolean newRecord = true;
        boolean showReport = true;

        do
        {
            int salespersonID;
            String salespersonName;
            String productType;
            int unitsSold = 0;
            double unitPrice;



            System.out.println("Please enter the Salesperson Inoformation.");
            System.out.print("Salesperson ID: ");
            salespersonID = userInput.nextInt();

            System.out.print("Salesperson Name: ");
            salespersonName = userInput.next();
            System.out.print("Product Type: ");
            productType = userInput.next();
            System.out.print("Units Sold: ");
            unitsSold = userInput.nextInt();
            System.out.print("Unit Price: ");
            unitPrice = userInput.nextDouble();

            if(salesPeople.size() == 0) 
            {
                salesPerson tmp = new salesPerson(salespersonID, salespersonName, productType, unitsSold, unitPrice);
                salesPeople.add(tmp);
            }
            else
            {
                for(int i=0; i < salesPeople.size(); i++) 
                {
                    if(salesPeople.get(i).getSalesPersonID() == salespersonID)
                    {
                        salesPeople.get(i).setUnitsSold(unitsSold);
                        break;
                    }
                    else
                    {
                        salesPerson tmp = new salesPerson(salespersonID, salespersonName, productType, unitsSold, unitPrice);
                        salesPeople.add(tmp);
                        break;
                    }
                  //System.out.println(salesPeople.get(i).getSalesPersonName());
                }
            }

            System.out.print("Would you like to enter more data?(y/n)");
            String askNew = userInput.next();
            newRecord = (askNew.toLowerCase().equals("y")) ? true : false;

        }
        while(newRecord == true);
Теги:
arraylist
sorting

1 ответ

3
Лучший ответ

Напишите пользовательский компаратор:

public SalesPersonComparator implements Comparator<salesPerson> {
    public int compare(final salesPerson p1, final salesPerson p2) {
        // get the comparison of the unit prices (in descending order, so compare p2 to p1)
        int comp = new Double(p2.getUnitPrice()).compareTo(new Double(p1.getUnitPrice()));

        // if the same
        if(comp == 0) {
            // compare the units sold (in descending order, so compare p2 to p1)
            comp = new Integer(p2.getUnitsSold()).compareTo(new Integer(p1.getUnitsSold()));
        }
        return comp;
    }
}

Редактировать (спасибо @Levenal):

Затем используйте Collections.sort() чтобы отсортировать список.

  • 1
    Если у вас есть Comparator, я думаю, что это Collections.sort (...), который вы можете использовать для заказа своего списка?
  • 0
    @ Levenal Где именно я размещаю код?
Показать ещё 1 комментарий

Ещё вопросы

Сообщество Overcoder
Наверх
Меню