Niloy007

Sarah's Final

May 30th, 2020
111
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import java.util.ArrayList;
  2. import java.util.Collection;
  3. import java.util.Collections;
  4. import java.util.Comparator;
  5.  
  6. class Cookie {
  7.     String name;
  8.     double price;
  9.  
  10.     public Cookie(String name, double price) {
  11.         this.name = name;
  12.         this.price = price;
  13.     }
  14. }
  15.  
  16. public class Main {
  17.     public static void main(String[] args) {
  18.         ArrayList<Cookie> cookies = new ArrayList<>();
  19.         Cookie c1 = new Cookie("Chocolate Chip", 30.0);
  20.  
  21.         cookies.add(c1);
  22.         cookies.add(new Cookie("Fortune", 20.0));
  23.         cookies.add(new Cookie("Peanut Butter", 35.0));
  24.         cookies.add(new Cookie("Sugar Cookies", 27.0));
  25.  
  26.         Cookie c2 = new Cookie("Oatmeal Raisin", 25.0);
  27.  
  28.         cookies.add(1, c1);
  29.         cookies.add(1, c1);
  30.  
  31.         // Code for question 5.a.i
  32.  
  33.         cookies.set(0, c2);
  34.  
  35.         // Code for question 5.a.ii
  36.         System.out.println("Before sort:");
  37.  
  38.         for(Cookie c : cookies) {
  39.             System.out.println(c.name + " " + c.price);
  40.         }
  41.  
  42.         // Code for question 5.b
  43.  
  44.         Collections.sort(cookies, new Comparator<Cookie>() {
  45.  
  46.             @Override
  47.             public int compare(Cookie o1, Cookie o2) {
  48.                 return Integer.valueOf((int)o2.price).compareTo((int)o1.price);
  49.             }
  50.         });
  51.  
  52.         System.out.println("\n\nAfter sort:");
  53.  
  54.         for(Cookie c : cookies) {
  55.             System.out.println(c.name + " " + c.price);
  56.         }
  57.  
  58.  
  59.     }
  60. }
RAW Paste Data