-3

I am also looking for potential ways that I can incorporate a for loop.

I am learning Java on my own and am terribly confused on how I can sort the below array by type and then by price. This question is not similar to one that has been previously posted, because the question flagged only involves Strings, while mine uses a combination of ints, Strings, and doubles. All of the past posts I have looked at on Overflow before making my own post have not involved doubles in any way.

This is what I have defined Item as.

public Item(int type, String name, double quantity, double price) {
        this.type = type;
        this.name = name;
        this.quantity = quantity;
        this.price = price;
    }

This is my array:

public static void main ()
    {Item [] shoppingItems = {new Item(2,"Cherry",9,1.35),
                    new Item(3,"Orange Juice",4,5.29),
                    new Item(5,"Hand Soap",2,1.77),
                    new Item(6,"Tooth Brush",3,4.55),
                    new Item(4,"Cupcake",3,2.95),
                    new Item(1,"Red Tomato Sauce",5.5,2.35),
                    new Item(3,"Chicken",1.9,2.48),
                    new Item(3,"Apple Pie",2,3.99),
                    new Item(7,"Bug Spray",1,9.28),
                    new Item(3,"Roast Beef",2.82,5.99),
                    new Item(5,"Light Bulb",3,3.92),
                    new Item(4,"Cookies",0.2,2.96),
                    new Item(2,"Watermelon",1.8,2.29)
                };
            }

How can I sort this array in ascending order by type? And also by price?

I looked into using Comparators, but they did not seem to work for my objective. I'm also not sure because price is a double.

Math is Life
  • 105
  • 3

3 Answers3

2

You can do this using Collections.sort method. Just need to pass a custom Comparator implementation as below.

    List<Item> list = Arrays.asList(shoppingItems);
    Collections.sort(list, new Comparator<Item>() {
        @Override
        public int compare(Item item1, Item item2) {
            int typeCompareResult = Integer.compare(item1.type, item2.type);
            if (typeCompareResult != 0) {
                return typeCompareResult;
            } else {
                return Double.compare(item1.price, item2.price);
            }
        }
    });

EDIT: This is old school way of doing things. For start this is good, but ultimately take advantage of Comparator.comparingInt added in Java 8 which is more concise. Refer KaNa0011's answer

Check Object ordering for more clarity.

shriyog
  • 938
  • 1
  • 13
  • 26
1

You can sort them by using a custom comparator object created by chaining Comparator.comparing(...) calls.

Comparator<Item> itemComparator = Comparator
  .comparingInt(Item::getType)
  .thenComparingDouble(Item::getPrice);

Arrays.sort(soppingItems, itemComparator);
sweet suman
  • 1,031
  • 8
  • 18
  • What's this class `Comparator` package references would be helpful – shriyog Jan 04 '19 at 03:36
  • 1
    [Comparator](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Comparator.html) was an interface that holds a function for comparing objects in java. Since Java 8, they added static and default methods for building comparator Fp-style – sweet suman Jan 04 '19 at 03:41
  • So, it's the same old `java.util.Comparator` with added methods in Java 8 release – shriyog Jan 04 '19 at 03:41
  • Is there a way to do this using a for loop? – Math is Life Jan 04 '19 at 05:20
  • There is. You need to select first which algorithm you need to implement. For example, [selection sort](https://en.wikipedia.org/wiki/Selection_sort) is one of the easiest algorithm to implement in a `for` loop - just 2 `for` loop that is nested, and a conditional statement that decides if the array elements should be swapped. – sweet suman Jan 04 '19 at 06:28
  • @KaNa0011 Thank you for the tip. I'm a little confused how to use the selection sort for the price though, because it's the fourth term of every new Item() set and not the first like it is for type. I think I have an idea of what to do for type, on the other hand. – Math is Life Jan 04 '19 at 06:39
  • The order of data in the constructor (`new Item()`) does not matter. It's up to you to order the sort in any way you want. – sweet suman Jan 04 '19 at 07:38
0
    List<Item> list = Arrays.asList(shoppingItems);
    Collections.sort(list,Comparator.comparingInt(Item::getType));
    System.out.println(list.toString());

Assume you have the corresponding getType() and toString() defined for your Item class

devildelta
  • 125
  • 2
  • 5