lambda|java8 lambda表达式

Klass 类

package com.arthur.dy.lambda; import java.util.List; /** * Created by arthur.dy.lee on 2017/4/4. */ public class Klass {private String klassName; private List studentList; public String getKlassName() { return klassName; }public void setKlassName(String klassName) { this.klassName = klassName; }public List getStudentList() { return studentList; }public void setStudentList(List studentList) { this.studentList = studentList; }}

Student 类
package com.arthur.dy.lambda; /** * Created by arthur.dy.lee on 2017/3/25. */ public class Student {publicintage; private Stringname; publicBoolean sex; public boolean getSex() { return sex; }public void setSex(boolean sex) { this.sex = sex; }public int getAge() { return age; }public void setAge(int age) { this.age = age; }public String getName() { return name; }public void setName(String name) { this.name = name; }public Student() { }public Student(int age, String name) { this.age = age; this.name = name; }public Student(int age, String name, boolean sex) { this.age = age; this.name = name; this.sex = sex; }}

User类
package com.arthur.dy.lambda; /** * Created by arthur.dy.lee on 2017/3/26. */ public class User { public intid; private String name; private String no; private inttel; public User() { }public User(int id, String name) { this.id = id; this.name = name; }public User(int id, String name, String no, int tel) { this.id = id; this.name = name; this.no = no; this.tel = tel; }public int getId() { return id; }public void setId(int id) { this.id = id; }public String getName() { return name; }public void setName(String name) { this.name = name; }public String getNo() { return no; }public void setNo(String no) { this.no = no; }public int getTel() { return tel; }public void setTel(int tel) { this.tel = tel; } }

单测 LambdaBaseTest
package com.arthur.dy.lambda; import com.alibaba.fastjson.JSONObject; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.*; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.IntSummaryStatistics; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.OptionalDouble; import java.util.Set; import java.util.function.Predicate; import java.util.stream.Collectors; import java.util.stream.Stream; /** * Created by arthur.dy.lee on 2017/3/25. */ public class LambdaBaseTest {// ThreadLocal 生成一个 DateFormatter实例,该实例是线程安全的 ThreadLocal localFormatter = ThreadLocal.withInitial(() -> new SimpleDateFormat()); public Listlist= new ArrayList(); public List studentList= new ArrayList(); public ListlanguageList = Arrays.asList("Java", "Scala", "C++", "Haskell", "Lisp"); public Klass klass; public List klassList = new ArrayList<>(); /** * 数据准备阶段 */ @Before public void setUp() {list.add("a1"); list.add("a2"); list.add("b1"); list.add("b2"); studentList.add(new Student(1, "gabriel", true)); studentList.add(new Student(2, "cindy", false)); studentList.add(new Student(3, "stone", true)); studentList.add(new Student(14, "arthur", true)); studentList.add(new Student(16, "Jack", true)); studentList.add(new Student(20, "Joe", true)); studentList.add(new Student(21, "alice", false)); klass = new Klass(); klass.setKlassName("一班"); klass.setStudentList(studentList); klassList.add(klass); studentList = new ArrayList<>(); studentList.add(new Student(5, "Donna", false)); studentList.add(new Student(11, "sunny", true)); studentList.add(new Student(14, "alex", true)); studentList.add(new Student(25, "Donna", false)); studentList.add(new Student(27, "Elizabeth", false)); studentList.add(new Student(31, "flex", true)); klass = new Klass(); klass.setKlassName("二班"); klass.setStudentList(studentList); klassList.add(klass); //formatter使用时: DateFormat formatter = localFormatter.get(); }@Test public void list1Test() { //只是简单遍历 studentList.forEach(p -> System.out.println(p.age + ", " + p.getName())); //等同时: for (Student p : studentList) { System.out.println(p.age + ", " + p.getName()); }List retList = list.stream().filter(e -> e.contains("a")).collect(Collectors.toList()); Assert.assertEquals(retList.size(), 2); retList = languageList.stream().filter(e -> e.contains("Scala")).collect(Collectors.toList()); Assert.assertEquals(retList.size(), 1); String str = retList.get(0); Assert.assertEquals("Scala", str); }@Test public void findFirstTest() { final Optional retOpt = languageList.stream().filter(e -> e.contains("Scala")).findFirst(); System.out.println(retOpt.get()); }/** * findFirest */ @Test public void findFirst2Test() { Optional retOpt = studentList.stream().filter(e -> e.age >= 2).findFirst(); String name = retOpt.get().getName(); Assert.assertEquals(name, "cindy"); Assert.assertTrue(retOpt.isPresent()); retOpt = studentList.stream().filter(e -> e.age >= 2).collect(Collectors.toList()).stream() .filter(p -> p.getName().equals("stone")).findFirst(); //正确的写法: if (retOpt.isPresent()) { Student student = retOpt.get(); Assert.assertEquals(student.getName(), "stone"); } }@Test public void streamTest1() { System.out.println("===============streamTest1 start==============="); String commonName = "超过2岁的"; studentList.stream() .filter(s -> s.getAge() >= 2) .forEach(s -> s.setName(commonName)); //forEach没有返回值 studentList.forEach(p -> System.out.println(p.getName())); System.out.println("===============streamTest1 end==============="); }/** * distinct去重 */ @Test public void distinctTest() { System.out.println("=============== distinctTest start ==============="); List languageList = Arrays.asList("1", "2", "3", "3", "lee", "haskell", "arthur"); languageList.stream().map(e -> e.toUpperCase()).forEach(e -> System.out.print(e + " ")); System.out.println("----"); languageList = Arrays.asList("1", "2", "3", "3", "4", "5", "5"); List retList = languageList.stream() .map(e -> new Integer(e)) .filter(e -> e % 2 != 0) .distinct() .collect(Collectors.toList()); retList.forEach(e -> System.out.print(e + " ")); System.out.println(""); System.out.println("=============== distinctTest end ==============="); }@Test public void iterator2List() { System.out.println("=============== iterator2List start ==============="); List studentList = new ArrayList<>(); Student p = new Student(10, "arthur"); studentList.add(p); p = new Student(11, "lee"); studentList.add(p); p = new Student(12, "susan"); studentList.add(p); p = new Student(10, "albert"); studentList.add(p); List userList = new ArrayList<>(); User u = new User(21, "arthur"); userList.add(u); u = new User(22, "susan"); userList.add(u); u = new User(23, "alice"); userList.add(u); u = new User(24, "alice"); userList.add(u); u = new User(25, "cinderlla"); userList.add(u); List retList = new ArrayList<>(); //old style for (User user : userList) { for (Student student : studentList) { if (user.getName().equals(student.getName())) { retList.add(student); } } } System.out.println("----------"); retList.forEach(e -> System.out.println(e.getName())); //lambda style 1 retList = studentList.stream().filter(c -> ( userList.stream().map(User::getName).collect(Collectors.toList()).contains(c.getName()) )).collect(Collectors.toList()); System.out.println("----- 如果把contains换成equals则不会出结果 -----"); retList.forEach(e -> System.out.println(e.getName())); //lambda style 2 【toList换成toSet会更高效】 retList = studentList.stream().filter(c -> ( userList.stream().map(User::getName).collect(Collectors.toSet()).contains(c.getName()) )).collect(Collectors.toList()); System.out.println("----------"); retList.forEach(e -> System.out.println(e.getName())); System.out.println("=============== iterator2List end ==============="); }/** * hashMap */ @Test public void hashMapTest() { System.out.println("=============== hashMapTest start ==============="); Map items = new HashMap<>(); items.put("A", 10); items.put("B", 20); items.put("C", 30); items.put("D", 40); items.put("E", 50); items.put("F", 60); Map ret = new HashMap<>(); items.forEach((k, v) -> { //System.out.println("item: " + k + ", Count: " + v); if (k.equals("E")) { System.out.println("-------"); System.out.println("hello E"); ret.put(k, v); } }); ret.forEach((k, v) -> System.out.println("retMap--> k:" + k + ", v:" + v)); System.out.println("=============== hashMapTest start ==============="); }@Test public void nullTest() { //Java 8, using stream.filter () to filter a List, and .findAny().orElse (null) to return an object conditional. String ret = languageList.stream() .filter(e -> "Java".equals(e)) .findAny() .orElse(null); Assert.assertEquals(ret, "Java"); ret = languageList.stream() .filter(e -> "Java1111".equals(e)) .findAny() .orElse(null); Assert.assertNull(ret); String name = studentList.stream() .filter(x -> "cindy".equals(x.getName())) .map(Student::getName)//convert stream to String .findAny() .orElse(null); Assert.assertEquals(name, "cindy"); }/** * 求平均值 */ @Test public void testAverageFromArray() { List users = Arrays.asList( new User(1, "Steve", "Vai", 40), new User(4, "Joe", "Smith", 32), new User(3, "Steve", "Johnson", 57), new User(9, "Mike", "Stevens", 18), new User(10, "George", "Armstrong", 24), new User(2, "Jim", "Smith", 40), new User(8, "Chuck", "Schneider", 34), new User(5, "Jorje", "Gonzales", 22), new User(6, "Jane", "Michaels", 47), new User(7, "Kim", "Berlie", 60) ); double average = users.stream().map(u -> u.getTel()).mapToDouble(f -> f.doubleValue()).average().getAsDouble(); System.out.println(average); final Double[] dbls = { 1.1, 1.2, 1.3, 1.4, 1.5 }; final double av = Stream.of(dbls).mapToDouble(d -> d).average().getAsDouble(); Assert.assertEquals(1.3, av, 0); }/** * 使用Predicate组合过滤条件 */ @Test public void combinePredicate() { Predicate startsWithJ = (n) -> n.startsWith("J"); Predicate fourLetterLong = (n) -> n.length() == 4; languageList.stream() .filter(startsWithJ.and(fourLetterLong)) .forEach((n) -> System.out.print("\nName, which starts with 'J' and four letter long is : " + n)); }/** * reduce有2种形式 * //1.无初始值累加 * T t = person.stream().reduce((a,b)->a+b); * //2.带初始值累加 * Optional t = person.stream().reduce("1",(a,b)->a+b); */ @Test public void mapReduceTest() { //List costBeforeTax = Arrays.asList(100, 200, 300, 400, 500); List costBeforeTax = Arrays.asList(2.0, 3.0, 5.0, 7.0, 11.0, 13.0, 17.0, 19.0, 23.0, 29.0); double bill = costBeforeTax.stream().map((cost) -> cost + .12 * cost).reduce((sum, cost) -> sum + cost).get(); System.out.println("Total : " + bill); }/** * IntSummaryStatistics 计算最大、最小、总和和平均值 */ @Test public void calculatingMaximumMinimumSumAverageTest() { List primes = Arrays.asList(2, 3, 5, 7, 11, 13, 17, 19, 23, 29); IntSummaryStatistics stats = primes.stream().mapToInt((x) -> x).summaryStatistics(); assertEquals(stats.getMax(), 29); assertEquals(stats.getMin(), 2); assertEquals(stats.getSum(), 129); assertEquals(stats.getAverage(), 12.9, 0); System.out.println("Highest prime number in List : " + stats.getMax()); System.out.println("Lowest prime number in List : " + stats.getMin()); System.out.println("Sum of all prime numbers : " + stats.getSum()); System.out.println("Average of all prime numbers : " + stats.getAverage()); }@Test public void minTest() { //List primes = Arrays.asList(2, 3, 5, 7, 11, 13, 17, 19, 23, 29); List numbers = Arrays.asList(2.0, 3.0, 5.0, 7.0, 11.0, 13.0, 17.0, 19.0, 23.0, 29.0); OptionalDouble average = numbers.stream() .mapToDouble(Double::doubleValue).average(); System.out.println(average.getAsDouble()); OptionalDouble min = numbers.stream().mapToDouble(Double::doubleValue).min(); assertEquals(min.getAsDouble(), 2.0, 0); System.out.println(min); }@Test public void list2Test() { List list = studentList.stream().filter(e -> e.getAge() > 10).collect(Collectors.toList()); assertEquals(list.size(), 5); List retList = studentList.stream().filter(e -> e.getAge() > 10).map(e -> e.getName().toUpperCase()) .collect(Collectors.toList()); String name = retList.get(0); assertEquals(name, "SUNNY"); name = retList.get(1); assertEquals(name, "ALEX"); list = studentList.stream().filter(e -> e.getAge() > 10).map(m -> { m.setName(m.getName().toUpperCase()); return m; }) .collect(Collectors.toList()); assertEquals(list.size(), 5); Student s = list.get(0); assertEquals(s.getName(), "SUNNY"); }/** * 使用flatMap 组合多个流 */ @Test public void combineList() {List list1 = Arrays.asList(1, 2); List list2 = Arrays.asList(3, 4); List together = Stream.of(list1, list2).flatMap(numbers -> numbers.stream()) .collect(Collectors.toList()); assertEquals(together.size(), 4); }@Test public void findInList() { //在班级列表中,找到年龄大于等于20岁的学生姓名Set names = klassList.stream().flatMap(e -> e.getStudentList().stream()).filter(s -> s.getAge() >= 20) .map(s -> s.getName().toUpperCase()).collect(Collectors.toSet()); System.out.println(names); assertEquals(names.size(), 5); }/** * 字符串链接 */ @Test public void stringJoinTest() { String ret = studentList.stream().map(Student::getName).collect(Collectors.joining(",", "[", "]")); System.out.println("stringJoinTest: " + ret); assertEquals(ret, "[Donna,sunny,alex,Donna,Elizabeth,flex]"); ret = studentList.stream().map(Student::getName).collect(Collectors.joining()); System.out.println("stringJoinTest: " + ret); }@Test public void listStrConcatTest() { List G7 = Arrays.asList("USA", "Japan", "France", "Germany", "Italy", "U.K.", "Canada"); String G7Countries = G7.stream().map(x -> x.toUpperCase()).collect(Collectors.joining(", ")); assertEquals(G7Countries, "USA, JAPAN, FRANCE, GERMANY, ITALY, U.K., CANADA"); System.out.println(G7Countries); }/** * groupBy */ @Test public void groupByTest() {Map retMap1 = studentList.stream().collect(Collectors.groupingBy(Student::getSex)); String ret = JSONObject.toJSONString(retMap1); System.out.println(ret); } }

BaseTest
package com.arthur.dy; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.AbstractTransactionalJUnit4SpringContextTests; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.transaction.annotation.Transactional; @RunWith(SpringJUnit4ClassRunner.class) //使用classpath,会自动去class下的目录去找,所以暂时把它放到了resource目录下。 @ContextConfiguration(locations = {"classpath:/junitTestContext.xml"}) @Transactional publicclass BaseTest extends AbstractTransactionalJUnit4SpringContextTests {}

【lambda|java8 lambda表达式】转载请注明:
http://blog.csdn.net/paincupid/article/details/66628010

    推荐阅读