Lambda学习案例
2018-11-08 本文已影响0人
梦想又照进现实
package Lambda;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;
enum Gender{
MALE,FEMALE
}
public class Person {
private String givenName;
private String surName;
private int age;
private Gender gender;
private String eMail;
private String phone;
private String address;
public static class Builder{
private String givenName="";
private String surName="";
private int age = 0;
private Gender gender = Gender.FEMALE;
private String eMail = "";
private String phone = "";
private String address = "";
public Person.Builder givenName(String givenName){
this.givenName = givenName;
return this;
}
public Person.Builder surName(String surName){
this.surName = surName;
return this;
}
public Person.Builder age (int val){
age = val;
return this;
}
public Person.Builder gender(Gender val){
gender = val;
return this;
}
public Person.Builder email(String val){
eMail = val;
return this;
}
public Person.Builder phoneNumber(String val){
phone = val;
return this;
}
public Person.Builder address(String val){
address = val;
return this;
}
public Person build(){
return new Person(this);
}
}
private Person(){
super();
}
private Person(Person.Builder builder){
givenName = builder.givenName;
surName = builder.surName;
age = builder.age;
gender = builder.gender;
eMail = builder.eMail;
phone = builder.phone;
address = builder.address;
}
public String getGivenName(){
return givenName;
}
public String getSurName(){
return surName;
}
public int getAge(){
return age;
}
public Gender getGender(){
return gender;
}
public String getEmail(){
return eMail;
}
public String getPhone(){
return phone;
}
public String getAddress(){
return address;
}
public void print(){
System.out.println(
"\nName: " + givenName + " " + surName + "\n" +
"Age: " + age + "\n" +
"Gender: " + gender + "\n" +
"eMail: " + eMail + "\n" +
"Phone: " + phone + "\n" +
"Address: " + address + "\n"
);
}
public String printCustom(Function<Person, String> f){
return f.apply(this);
}
public void printWesternName(){
System.out.println("\nName: " + this.getGivenName() + " " + this.getSurName() + "\n" +
"Age: " + this.getAge() + " " + "Gender: " + this.getGender() + "\n" +
"EMail: " + this.getEmail() + "\n" +
"Phone: " + this.getPhone() + "\n" +
"Address: " + this.getAddress());
}
public void printEasternName(){
System.out.println("\nName: " + this.getSurName() + " " + this.getGivenName() + "\n" +
"Age: " + this.getAge() + " " + "Gender: " + this.getGender() + "\n" +
"EMail: " + this.getEmail() + "\n" +
"Phone: " + this.getPhone() + "\n" +
"Address: " + this.getAddress());
}
@Override
public String toString(){
return "Name: " + givenName + " " + surName + "\n" + "Age: " + age + " Gender: " + gender + "\n" + "eMail: " + eMail + "\n";
}
public static List<Person> createShortList(){
List<Person> people = new ArrayList<>();
people.add(
new Person.Builder()
.givenName("zhang")
.surName("3")
.age(21)
.gender(Gender.MALE)
.email("zhangsan@example.com")
.phoneNumber("0571-1214678")
.address("zhang3 address")
.build()
);
people.add(
new Person.Builder()
.givenName("li")
.surName("4")
.age(25)
.gender(Gender.FEMALE)
.email("li4@example.com")
.phoneNumber("0571-1214678")
.address("li4 address")
.build()
);
people.add(
new Person.Builder()
.givenName("wang")
.surName("5")
.age(25)
.gender(Gender.MALE)
.email("wang5@example.com")
.phoneNumber("0571-1214678")
.address("wang5 address")
.build()
);
people.add(
new Person.Builder()
.givenName("zhang")
.surName("1")
.age(45)
.gender(Gender.MALE)
.email("zhang1@example.com")
.phoneNumber("0571-1214678")
.address("zhang1 address ")
.build()
);
return people;
}
}
package Lambda;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Predicate;
public class SearchCriteria {
private final Map<String, Predicate<Person>> searchMap = new HashMap<>();
private SearchCriteria() {
super();
initSearchMap();
}
private void initSearchMap() {
Predicate<Person> allDrivers = p -> p.getAge() >= 16;
Predicate<Person> allDraftees = p -> p.getAge() >= 18 && p.getAge() <= 25 && p.getGender() == Gender.MALE;
Predicate<Person> allPilots = p -> p.getAge() >= 23 && p.getAge() <= 65;
searchMap.put("allDrivers", allDrivers);
searchMap.put("allDraftees", allDraftees);
searchMap.put("allPilots", allPilots);
}
public Predicate<Person> getCriteria(String PredicateName) {
Predicate<Person> target;
target = searchMap.get(PredicateName);
if (target == null) {
System.out.println("Search Criteria not found... ");
System.exit(1);
}
return target;
}
public static SearchCriteria getInstance() {
return new SearchCriteria();
}
}
** ForEach **
package Lambda;
import java.util.List;
public class Test01ForEach {
public static void main(String[] args) {
List<Person> pl = Person.createShortList();
System.out.println("\n=== Western Phone List ===");
pl.forEach( p -> p.printWesternName() );
System.out.println("\n=== Eastern Phone List ===");
pl.forEach(Person::printEasternName);
System.out.println("\n=== Custom Phone List ===");
pl.forEach(p -> { System.out.println(p.printCustom(r -> "Name: " + r.getGivenName() + " EMail: " + r.getEmail())); });
}
}
***Filter ***
package Lambda;
import java.util.List;
public class Test02Filter {
public static void main(String[] args) {
List<Person> pl = Person.createShortList();
SearchCriteria search = SearchCriteria.getInstance();
System.out.println("\n=== Western Pilot Phone List ===");
pl.stream().filter(search.getCriteria("allPilots"))
.forEach(Person::printWesternName);
System.out.println("\n=== Eastern Draftee Phone List ===");
pl.stream().filter(search.getCriteria("allDraftees"))
.forEach(Person::printEasternName);
}
}
*** toList***
package Lambda;
import java.util.List;
import java.util.stream.Collectors;
public class Test03toList {
public static void main(String[] args) {
List<Person> pl = Person.createShortList();
SearchCriteria search = SearchCriteria.getInstance();
// Make a new list after filtering.
List<Person> pilotList = pl
.stream()
.filter(search.getCriteria("allPilots"))
.collect(Collectors.toList());
System.out.println("\n=== Western Pilot Phone List ===");
pilotList.forEach(Person::printWesternName);
}
}
*** toMap ***
package Lambda;
import java.util.List;
import java.util.OptionalDouble;
public class Test04Map {
public static void main(String[] args) {
List<Person> pl = Person.createShortList();
SearchCriteria search = SearchCriteria.getInstance();
// Calc average age of pilots old style
System.out.println("== Calc Old Style ==");
int sum = 0;
int count = 0;
for (Person p:pl){
if (p.getAge() >= 23 && p.getAge() <= 65 ){
sum = sum + p.getAge();
count++;
}
}
long average = sum / count;
System.out.println("Total Ages: " + sum);
System.out.println("Average Age: " + average);
// Get sum of ages
System.out.println("\n== Calc New Style ==");
long totalAge = pl
.stream()
.filter(search.getCriteria("allPilots"))
.mapToInt(p -> p.getAge())
.sum();
// Get average of ages
OptionalDouble averageAge = pl
.parallelStream()
.filter(search.getCriteria("allPilots"))
.mapToDouble(p -> p.getAge())
.parallel()
.average();
System.out.println("Total Ages: " + totalAge);
System.out.println("Average Age: " + averageAge.getAsDouble());
System.out.println(String.format("it's %d ad %d",1,2));
}
}
*** main 方法***
package Lambda;
import java.util.List;
import java.util.stream.Collectors;
/**
* Created by 80374563 on 2018/11/7.
*/
public class LambdaStaret {
public static void main(String[] args) {
long st = System.currentTimeMillis();
System.out.println("done : " + (System.currentTimeMillis() - st) + " msecs");
//Lambda
Runnable r = ()-> {int i=9; System.out.println(i); };
r.run();
//2.
List<Person> pl = Person.createShortList();
SearchCriteria search = SearchCriteria.getInstance();
// Make a new list after filtering.
List<Person> pilotList = pl
.stream()
.filter(search.getCriteria("allPilots"))
.collect(Collectors.toList());
System.out.println("\n=== Western Pilot Phone List ===");
pilotList.forEach(Person::printWesternName);
}
}