java8-lambda實戰

前言

java8推出已經好久了,然而其新特性卻幾乎沒有怎麼用過。緣由是既然已有的只是知足需求何須去學習新的?然而,隨着敲代碼愈來愈多,業務上有不少臃腫繁瑣的判斷校驗之類的代碼,使得代碼很長並且可讀性不好。因而,從新撿起了java8。java

[TOC]編程

實際用法

這裏是實際代碼中使用過的簡單套式作法,隨時更新。app

list過濾

將知足需求的list元素篩選出來。 filter 返回一個boolean值,true的時候經過並放入一個stream裏。ide

接收一個參數list,須要根據元素的某些條件來判斷是否知足需求,將知足需求或者不知足需求的元素拿出來。這個正常代碼也簡單,遍歷list,if判斷,add賦值到結果集。然而,這個串代碼僅僅是一個方法的前置校驗部分,這會使得這個方法臃腫難以閱讀。雖然重構提取函數能夠提升可讀性,但分散的代碼管理也是麻煩。因此,java8的流式函數編程就適合:函數

List<TipUI> badList = tips.stream().filter(tipUI -> StringUtils.isBlank(tipUI.getGaiaId())).collect(Collectors.toList());

list重組

操做list元素中的部分屬性構建新的list map用來轉換元素學習

有個users列表,我想要或者這些user的id列表。code

@Test
public void testMap(){
    List<User> users = Arrays.asList(
            new User(1,"Ryan"),
            new User(2, "Leslie"),
            new User(3, "Test")
    );
    //collect user ids
    Stream<Integer> integerStream = users.stream().map(User::getId);
    List<Integer> ids = integerStream.collect(Collectors.toList());
    Assert.assertEquals("[1, 2, 3]",ids.toString());

    //collect user names
    List<String> names = users.stream().map(user -> user.getName()).collect(Collectors.toList());
    Assert.assertEquals("[Ryan, Leslie, Test]", names.toString());
}

list過濾並重組

仍舊使用filtermap。此次演示構建過程。orm

將person列表轉換爲student列表:排序

Stream<Student> students = persons.stream()
      .filter(p -> p.getAge() > 18)
      .map(new Function<Person, Student>() {
                  @Override
                  public Student apply(Person person) {
                     return new Student(person);
                  }
              });

簡化map的function爲lambda:ip

Stream<Student> map = persons.stream()
        .filter(p -> p.getAge() > 18)
        .map(person -> new Student(person));

由於map的用法中參數的使用只經過傳遞,那麼(前提是student有參數爲person的構造器):

Stream<Student> map = persons.stream()
        .filter(p -> p.getAge() > 18)
        .map(Student::new);

收集爲list:

List<Student> students = persons.stream()
        .parallel()
        .filter(p -> p.getAge() > 18)  // filtering will be performed concurrently
        .sequential()
        .map(Student::new)
        .collect(Collectors.toCollection(ArrayList::new));

list排序

對list進行排序

好比從大到小排序:

@Test
public void testListSortDesc(){
    Integer a = 12,b = 23;
    Assert.assertEquals(-1, a.compareTo(b));

    List<Integer> list = Arrays.asList(null,a,b,null);
    //large > small
    List<Integer> sorted = list.stream()
            .sorted(( m, n) ->{
                if (m==null) return 1;
                if (n==null) return -1;
                return n.compareTo(m);
            })
            .collect(Collectors.toList());
    Assert.assertEquals("[23, 12, null, null]", sorted.toString());
}

Map排序

map按照value排序,逆序:

@Test
public void testHashMapSortByValueDesc(){
    Map<String, Integer> unsortMap = new HashMap<>();
    unsortMap.put("z", 10);
    unsortMap.put("b", 5);
    unsortMap.put("a", 6);
    unsortMap.put("c", 20);
    unsortMap.put("d", 1);
    unsortMap.put("e", 7);
    unsortMap.put("y", 8);
    unsortMap.put("n", 99);
    unsortMap.put("j", 50);
    unsortMap.put("m", 2);
    unsortMap.put("f", 9);

    LinkedHashMap<String, Integer> orderMap = unsortMap.entrySet().stream()
            .sorted(Map.Entry.comparingByValue(Collections.reverseOrder()))
            .collect(Collectors.toMap(
                    Map.Entry::getKey,
                    Map.Entry::getValue,
                    (e1, e2) -> e1,
                    LinkedHashMap::new
            ));
    Assert.assertEquals("{n=99, j=50, c=20, z=10, f=9, y=8, e=7, a=6, b=5, m=2, d=1}",
            orderMap.toString());
}

自定義map類型:

//re-init brandScoreMap
LinkedHashMap<String, Score> scoreMap = brandScoreMap.entrySet().stream()
                .collect(Collectors.toMap(p -> p.getKey(), p -> new Score(p.getValue(), caculateGrade(p.getValue())), (e1, e2) -> e1, LinkedHashMap::new));

基礎知識

此處留着等待系統學習的時候補上。

相關文章
相關標籤/搜索