-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.

4
  • you wan to sort by type and by price? which comes first ? Commented Jan 4, 2019 at 2:58
  • @talex That post doesn't teach me how to use Comparator with double, only ints and Strings Commented Jan 4, 2019 at 3:07
  • @MathisLife with doubles all exactly same. Commented Jan 4, 2019 at 3:08
  • @mkjh type comes first Commented Jan 4, 2019 at 3:26

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Do I need anything else before or after this code? What sort of imports should I add?
How do I solve a NullPointerException error?
My bad, it's working now
Is there a way to do this using a for loop for price?
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);

7 Comments

What's this class Comparator package references would be helpful
Comparator 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
So, it's the same old java.util.Comparator with added methods in Java 8 release
Is there a way to do this using a for loop?
There is. You need to select first which algorithm you need to implement. For example, 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.
|
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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.