简体   繁体   中英

How to sort a list of my objects

I've been coding for hours now trying to finish my assignment. Now that I am done, I would like to add a method that sorts the value of the customers. So that customer 2 comes on top and 5 last. How do I do that?

Here is the code for the first class:

public class Customer {

    private int customerNumber;
    private int purchases;
    private int shippingCost;
    private int productPrice;

    public int getProductPrice() {
        return productPrice;
    }

    public void setProductPrice(int productPrice) {
        this.productPrice = productPrice;
    }

    public int getPurchases() {
        return purchases;
    }

    public Customer(int purchases, int shippingCost, int productPrice) {
        this.purchases = purchases;
        this.shippingCost = shippingCost;
        this.productPrice = productPrice;
    }

    public void setPurchases(int purchases) {
        this.purchases = purchases;
    }

    public int getShippingCost() {
        return shippingCost;
    }

    public void setShippingCost(int shippingCost) {
        this.shippingCost = shippingCost;
    }

    protected int calculateValue() {
        int value=purchases*(productPrice-shippingCost);
        return value;
    }

    public int getCustomerNumber() {
        return customerNumber;
    }

    public void setCustomerNumber(int customerNumber) {
        this.customerNumber = customerNumber;
    }

The second class:

public class Subscriber extends Customer{

    private int years;
    private int fee;

    public Subscriber(int purchases, int shippingCost, int productPrice) {
        super(purchases, shippingCost,  productPrice);
    }

    public Subscriber(int purchases, int shippingCost, 
            int productPrice,int _years,int _fee) {
        super(purchases, shippingCost, productPrice);
        years=_years;
        fee=_fee;
    }

    public int getYears() {
        return years;
    }

    public void setYears(int years) {
        this.years = years;
    }

    public int getFee() {
        return fee;
    }

    public void setFee(int fee) {
        this.fee = fee;
    }

    protected int calculateSubscriptionValue() {
        return years*fee;
    }

    protected int calculateValue(){
        int value=super.calculateValue();   
        value+=calculateSubscriptionValue();
        return value;
    }

Third class:

public class BusinessSubscriber extends Subscriber{

    public BusinessSubscriber(int purchases, int shippingCost, int productPrice, int _years, int _fee) {
        super(purchases, shippingCost, productPrice, _years, _fee);
    }
    private double supportCost;
    private double supportTime;

    public double getSupportCost() {
        return supportCost;
    }
    public void setSupportCost(double supportCost) {
        this.supportCost = supportCost;
    }
    public double getSupportTime() {
        return supportTime;
    }
    public void setSupportTime(double supportTime) {
        this.supportTime = supportTime;
    }

    //override method: // skriv över den // problem med denna metod. uträkningsfel
    protected int calculateValue(){
        int value=super.calculateValue();   
        value+=calculateSubscriptionValue() - calculateSubscriptionValue();
        return value;
    }
}

Last and the main class:

public class printValue {

    public static void main(String[] args) {
        System.out.println("Unsorted version without DataStructure");
        System.out.println("-----------------------");
        BusinessSubscriber num1 = new BusinessSubscriber(3, 33, 99, 8, 78); 

        num1.setCustomerNumber(1);

        num1.setPurchases(3);
        num1.setShippingCost(33);
        num1.setYears(8);
        num1.setSupportTime(2);
        num1.setProductPrice(99);
        num1.setFee(78);
        num1.setSupportCost(25);
        System.out.println("Customer number: " + num1.getCustomerNumber() + " is worth " + num1.calculateValue() + "!");

        BusinessSubscriber num2 = new BusinessSubscriber (0, 0, 99, 18, 78);

        num2.setCustomerNumber(2);

        num2.setPurchases(0);
        num2.setShippingCost(0);
        num2.setYears(18);
        num2.setSupportTime(7);

        num2.setProductPrice(99);
        num2.setFee(78);
        num2.setSupportCost(25);

        System.out.println("Customer number: " + num2.getCustomerNumber() + " is worth " + num2.calculateValue() + "!");

        BusinessSubscriber num3 = new BusinessSubscriber (0, 0, 99, 8, 78);

        num3.setCustomerNumber(3);

        num3.setPurchases(0);
        num3.setShippingCost(0);
        num3.setYears(8);
        num3.setSupportTime(0);

        num2.setProductPrice(99);
        num2.setFee(78);
        num2.setSupportCost(25);

        System.out.println("Customer number: " + num3.getCustomerNumber() + " is worth " + num3.calculateValue() + "!");

        //  int purchases, int shippingCost, int productPrice, int _years, int _fee 

        Subscriber num4 = new Subscriber (12, 33, 99, 5, 78);

        num4.setCustomerNumber(4);

        num4.setPurchases(12);
        num4.setShippingCost(33);
        num4.setYears(5);

        num4.setProductPrice(99);
        num4.setFee(78);

        System.out.println("Customer number: " + num4.getCustomerNumber() + " is worth " + num4.calculateValue() + "!");

        Customer num5 = new Customer (8, 33, 99);

        num5.setCustomerNumber(5);

        num5.setPurchases(8);
        num5.setShippingCost(33);
        num5.setProductPrice(99);

        System.out.println("Customer number: " + num5.getCustomerNumber() + " is worth " + num5.calculateValue() + "!");

        // sortera efter calculatevalue metoden i businesssubsriber
}

The output of the code:

Customer number: 1 is worth 822!
Customer number: 2 is worth 1404!
Customer number: 3 is worth 624!
Customer number: 4 is worth 1182!
Customer number: 5 is worth 528!

I would like customer number 2 to be on top and 5 last, ie sort them. How do I do that? Thank you.

I tried this, but is that enough?

Integer [] sort = {num1.calculateValue(), num2.calculateValue(), num3.calculateValue(), num4.calculateValue(), num5.calculateValue()};

List<Integer> l1 = Arrays.asList(sort);

Collections.sort(l1);
System.out.println("Values sorted: " + l1);

But a more efficient way would be to put it all in a map, loop through it and then print it. How do I do that?

Also, I tried to edit the text as much as I can so it does not look messy.

If you are sorting your customers based on calculateValue() may b you can do like this:

Map sortedCustomer= new TreeMap();
sortedCustomer.put(num1.calculateValue(),num1);
sortedCustomer.put(num2.calculateValue(),num2);
sortedCustomer.put(num3.calculateValue(),num3);
sortedCustomer.put(num4.calculateValue(),num4);
sortedCustomer.put(num5.calculateValue(),num5);
//sortedCustomer is in ascending order...reverse it
sortedCustomerDescending =(TreeSet)sortedCustomer.descendingSet();
//get entrySet
  Set set = sortedCustomerDescending.entrySet();
  // Get an iterator
  Iterator i = set.iterator();
  // Display elements
  while(i.hasNext()) {
     Map.Entry me = (Map.Entry)i.next();
  //print the entries
     System.out.print(me.getKey() + ": ");
     System.out.println(me.getValue());
  }

I assume you want to sort in descending order.

You need to pass implement a Comaprator and pass it to Collections#sort method along with a List holding the objects you want to sort.

Something liek this should do it

public void testSort() {
    List<Customer> cL = Arrays.asList(new Customer(1, 822), 
            new Customer(2, 1404), 
            new Customer(3, 624), 
            new Customer(4, 1182), 
            new Customer(5, 528));
    Collections.sort(cL, new Comparator<Customer>() {
        @Override
        public int compare(Customer o1, Customer o2) {
            return o2.getCalc() - o1.getCalc();
        }
    });

    for( Customer c : cL) {
        System.out.println("Customer number: " + c.getCustomerNumber() 
                + " is worth " + c.getCalc() + "!");
    }
}

Output:

Customer number: 2 is worth 1404!
Customer number: 4 is worth 1182!
Customer number: 1 is worth 822!
Customer number: 3 is worth 624!
Customer number: 5 is worth 528!

For simplicity I have added a filed calc in Customer itself, you probably want to implement Comparator for the BusinessSubscriber class as the the value you are looking for sorting with comes from it.

Your Customer class should implement Comparable interface

public class Customer implements Comparable<Customer>{

You should override its compareTo method

@Override
public int compareTo(Customer cus) {
int calculatedValue = cus.calculateValue();
return calculatedValue - this.calculateValue();
}

Finally in your PrintValue class, add those customers to ArrayList and use Collections.sort

ArrayList<Customer> custList = new ArrayList<>();
custList.add(num1);
custList.add(num2);
custList.add(num3);
custList.add(num4);
custList.add(num5);

Collections.sort(custList);

for (Iterator iterator = custList.iterator(); iterator.hasNext();) {
    Customer customer = (Customer) iterator.next();
    System.out.println("Customer number: " + customer.getCustomerNumber() + " is worth " + customer.calculateValue() + "!");
}

If you have a list of objects, you can sort it with Collections.sort .

Stupid example (not compiled or run):

Collections.sort(listOfUsers, new Comparator<User>() {
    @Override
    public int compare(User u1, User u2) {
        return Integer.compare(u1.getAge(), u2.getAge());
    }
});

This comparison may not be exactly what you need to do, but you get the idea :-)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM