Last active
December 17, 2015 09:04
-
-
Save prahladyeri/0577b5a01ccaa8206e80 to your computer and use it in GitHub Desktop.
Rockstar Java Dev series: Using Lambda expressions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.ArrayList; | |
import java.util.List; | |
import java.util.function.Predicate; | |
interface ProductFilter | |
{ | |
public boolean run(Product p); | |
} | |
public class Product | |
{ | |
public String name; | |
public double price; | |
public String size; | |
//Navie approach | |
public static List<Product> search(List<Product> stock, String name) | |
{ | |
ArrayList<Product> r = new ArrayList<Product>(); | |
for (Product p : stock) | |
{ | |
if (p.name.compareTo(name)==0) { | |
r.add(p); | |
} | |
} | |
return r; | |
} | |
//Classic Java Programmer approach | |
public static List<Product> searchWithRange(List<Product> stock, String name, double minValue, double maxValue) | |
{ | |
ArrayList<Product> r = new ArrayList<Product>(); | |
for (Product p : stock) | |
{ | |
if (p.name.compareTo(name)==0 && (p.price>=minValue && p.price<=maxValue)) { | |
r.add(p); | |
} | |
} | |
return r; | |
} | |
//Expert Java Programmer approach | |
public static List<Product> searchWithInterface(List<Product> stock, ProductFilter filter) | |
{ | |
ArrayList<Product> r = new ArrayList<Product>(); | |
for (Product p : stock) | |
{ | |
if (filter.run(p)) { | |
r.add(p); | |
} | |
} | |
return r; | |
} | |
//Rockstar Java Programmer approach | |
public static List<Product> searchWithLambda(List<Product> stock, Predicate<Product> filter) | |
{ | |
ArrayList<Product> r = new ArrayList<Product>(); | |
for (Product p : stock) | |
{ | |
if (filter.test(p)) { | |
r.add(p); | |
} | |
} | |
return r; | |
} | |
public static void main(String[] args) | |
{ | |
ArrayList<Product> list = new ArrayList<Product>(); | |
list.add(new Product(){{ | |
name = "foo"; | |
size = "15in"; | |
price=25; | |
}}); | |
//List<Product> r = Product.search(list,"foo"); //naive | |
//List<Product> r = Product.searchWithRange(list,"foo",10,50); //classic | |
//~ List<Product> r = Product.searchWithInterface(list,new ProductFilter(){ | |
//~ public boolean run(Product p) { | |
//~ return (p.name=="foo" && (p.price>=10 && p.price<=50) && p.size=="15in"); | |
//~ } | |
//~ }); //expert | |
//~ List<Product> r = Product.searchWithInterface(list, | |
//~ (Product p) -> (p.name=="foo" && (p.price>=10 && p.price<=50) && p.size=="15in")); //rockstar1 | |
List<Product> r = Product.searchWithLambda(list, | |
(Product p) -> (p.name=="foo" && (p.price>=10 && p.price<=50) && p.size=="15in")); //rockstar2 | |
System.out.println(r.size()); | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment