Sort a list with a lambda expression

  The Java code snippet shows a class Answer with a method sortList that sorts a list of Item objects based on their price using a lambda expression. 

Here's the full code with some explanations and a test example added:

import java.util.ArrayList;

import java.util.List;


class Answer {


    // Change these boolean values to control whether you see

    // the expected answer and/or hints.

    static boolean showExpectedResult = false;

    static boolean showHints = false;


    // Return the largest number in the 'numbers' array.

    static List<Item> sortList(List<Item> items) {

        List<Item> result = new ArrayList<>(items);

        // Sort the result list using a lambda expression.

        result.sort((a, b) -> Float.compare(a.getPrice(), b.getPrice()));

        return result;

    }


    public static class Item {

        int id;

        String name;

        float price;


        public Item(int id, String name, float price) {

            this.id = id;

            this.name = name;

            this.price = price;

        }


        public int getId() {

            return id;

        }


        public void setId(int id) {

            this.id = id;

        }


        public String getName() {

            return name;

        }


        public void setName(String name) {

            this.name = name;

        }


        public float getPrice() {

            return price;

        }


        public void setPrice(float price) {

            this.price = price;

        }


        @Override

        public String toString() {

            return "[" + this.id + ", " + this.name + ", " + this.price + "]";

        }

    }


    public static void main(String[] args) {

        // Create a list of items

        List<Item> items = List.of(

            new Item(1, "Item1", 10.0f),

            new Item(2, "Item2", 5.0f),

            new Item(3, "Item3", 20.0f)

        );


        // Sort the list by price

        List<Item> sortedItems = sortList(items);


        // Print sorted items

        System.out.println("Sorted Items:");

        sortedItems.forEach(System.out::println);

    }

}

Explanation

  1. Sorting with Lambda Expression:

    • result.sort((a, b) -> Float.compare(a.getPrice(), b.getPrice())); sorts the result list of Item objects based on the price attribute. The Float.compare method is used to handle the comparison of float values correctly.
  2. Item Class:

    • The Item class has attributes idname, and price. It includes getters and setters, a constructor for initialization, and a toString method to provide a readable string representation of the object.
  3. Test Example in main Method:

    • The main method demonstrates how to use the sortList method by creating a list of Item objects, sorting them, and printing the sorted list.

Key Points

  • Lambda Expression: In the result.sort method, the lambda expression (a, b) -> Float.compare(a.getPrice(), b.getPrice()) is used to compare the prices of two Item objects.
  • Sorting Method: The sort method modifies the list in place, so the sorted list is returned and can be used directly.

Comments

Popular posts from this blog

Luhn Algorithm

JWT (JSON Web Token)

Security in General