Created
October 20, 2014 08:01
-
-
Save cfierbin/6de192b7ae432508b2ce to your computer and use it in GitHub Desktop.
Java 8 Syntactic Sugar Makes Practice For Java Advanced Certification More Enjoyable
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
package quizzes; | |
import java.util.ArrayList; | |
import java.util.Comparator; | |
import java.util.List; | |
public class Practice { | |
private static List<Product> products; | |
public static void main(String[] args) { | |
products = new ArrayList<Product>(); | |
Product aBook = new Product ("A book for programmers", 10); | |
Product anotherBook = new Product("Another programming book", 7); | |
Product poemBook = new Product("Poems"); | |
Product aNovel = new Product("A Journal"); | |
Product recipes = new Product("Cook Book", 9); | |
products.add(aBook); | |
products.add(anotherBook); | |
products.add(poemBook); | |
products.add(aNovel); | |
products.add(recipes); | |
products.stream() | |
.sorted(new CompareProducts()) | |
.forEach(product -> { | |
System.out.println(product.name + " " + product.customerLikes); | |
}); | |
} | |
} | |
class Product{ | |
String name; | |
Integer customerLikes; | |
public Product(String name, Integer likes){ | |
this.name = name; | |
customerLikes = likes; | |
} | |
public Product(String name){ | |
this.name = name; | |
} | |
} | |
class CompareProducts implements Comparator<Product>{ | |
@Override | |
public int compare(Product arg0, Product arg1) { | |
if(arg0.customerLikes == null) return 1; | |
if(arg1.customerLikes == null) return -1; | |
return arg0.customerLikes < arg1.customerLikes ? 1:-1; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment