Skip to content

Instantly share code, notes, and snippets.

@magnusram05
Last active November 5, 2019 04:23
Show Gist options
  • Save magnusram05/88a7592045792737d9fa37612825fed0 to your computer and use it in GitHub Desktop.
Save magnusram05/88a7592045792737d9fa37612825fed0 to your computer and use it in GitHub Desktop.
Java 8: Lambda Expression, Functional Interface and Stream
public class ProductUtil {
private static final Comparator<Product> sortByRatingAscStrategy = (product1, product2) -> {
if (product1 == null || product2 == null)
return -1;
return Double.compare(product1.getRating(), product2.getRating());
};
public static void main(String [] args){
List<Product> productList = new ArrayList<>(2);
productList.add(new Product("Model-1", 4, 129));
productList.add(new Product("Model-2", 4.5, 139));
/*
Following sort invocations produce the same result
They only differ in the way lambda expression is being used
*/
//Lambda expression used directly
Collections.sort(productList, (product1, product2) -> {
if (product1 == null || product2 == null)
return -1;
return Double.compare(product1.getRating(), product2.getRating());
});
//Lambda expression defined as a class variable for reuse
Collections.sort(productList, sortByRatingAscStrategy);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment