In Java 8 with lambda functions, it is now very easy to compare two floats in a list of objects. In this example, I use both lambda functions and functional operations (new functions in Java 8). Basically you can try this example. This example organizes people by floats that represent height:
List<Person> people = Person.createStandardList(); // create a list with 2 standard users Collections.sort(people, (Person p1, Person p2) -> Float.compare(p1.height_in_meter, p2.height_in_meter)); people.stream().forEach((p) -> { // functional operation p.printName(); });
This is my Person class.
public class Person { public static List<Person> createStandardList() { List<Person> people = new ArrayList<>(); Person p = new Person(); p.name = "Administrator"; p.surname = "admin"; p.address = "Via standard 1"; p.age = 26; p.sex = 'M'; p.height_in_meter = 1.70f; p.weight_in_kg = 68.50f; people.add(p); p = new Person(); p.name = "First"; p.surname = "Creator"; p.address = "Via standard 2"; p.age = 30; p.sex = 'F'; p.height_in_meter = 1.80f; p.weight_in_kg = 58.50f; people.add(p); p = new Person(); p.name = "Second"; p.surname = "Creator"; p.address = "Via standard 3"; p.age = 20; p.sex = 'F'; p.height_in_meter = 1.30f; p.weight_in_kg = 48.50f; people.add(p); return people; } public String name; public String surname; public String address; public int age; public char sex; public float height_in_meter; public float weight_in_kg; public String getName() { return name; } public String getSurname() { return surname; } public float getHeight_in_meter() { return high_in_meter; } public float getWeight_in_kg() { return weight_in_kg; } public void printName() { System.out.println(this.name); } }
Output:
Second
Administrator
First
So, I think that in this example it is easier to understand the functions of JAVA 8. In the documentation you are trying to use a similar example, but with strings using a different method. ( Oracle's official documentation on lambda functions with an example collection )
source share