Lambdas example for comparator

package net.codejava.lambda;

import java.util.*;

public class LambdaComparatorExample {
public static void main(String[] args) {
Book book1 = new Book("Head", 38.9f);
Book book2 = new Book("Thinking", 30.0f);
Book book3 = new Book("Effective", 50.0f);
Book book4 = new Book("Code", 42.5f);

List listBooks = Arrays.asList(book1, book2, book3, book4);

System.out.println("Before sorting:");
System.out.println(listBooks);

Comparator titleComparator = new Comparator() {
public int compare(Book book1, Book book2) {
return book1.getTitle().compareTo(book2.getTitle());
}
};

Collections.sort(listBooks, titleComparator);

System.out.println("\nAfter sorting by title:");
System.out.println(listBooks);

Comparator descPriceComp = (Book b1, Book b2) -> (int) (b2.getPrice() - b1.getPrice());

Collections.sort(listBooks, descPriceComp);

System.out.println("\nAfter sorting by descending price:");
System.out.println(listBooks);

Collections.sort(listBooks, (b1, b2) -> (int) (b1.getPrice() - b2.getPrice()));

System.out.println("\nAfter sorting by ascending price:");
System.out.println(listBooks);
}
}

class Book {
private String title;
private float price;

Book(String title, float price) {
this.title = title;
this.price = price;
}

String getTitle() {
return this.title;
}

void setTitle(String title) {
this.title = title;
}

float getPrice() {
return this.price;
}

void setPrice(float price) {
this.price = price;
}

public String toString() {
return this.title + "-" + this.price;
}
}


sorting before java 8

public void someLoop(List things) {
    for(Thing t : things) {
        System.out.println(t);
    }
}

after java 8
public void someLoop(List things) {
    Stream stream = things.stream();
    stream.forEach((Thing t) -> System.out.println(t));
}
In the above example, we used a lambda expression, that is a function, taking a single thing and printing it out, returning nothing. This cleans up the code somewhat, but we can do better. Java 8 is able to guess types for lambda expressions. So we can simply replace (Thing t) with (t). With that we made our expression even simpler, but the method is still just using a single method, and Java provides for an even better way of doing.
public void someLoop(List things) {
       things.stream().forEach(System.out::println);
}

Comments

Popular posts from this blog

JPA JPQL advantages and disadvantage

Java8 Collectors mapping and joining function usages