用stream重構for循環

用stream替代for,替換後方便併發執行

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import static java.util.stream.Collectors.toList;

public class TestMaxBy {

    public static void main(String[] args) {
        List<Human> humans = Arrays.asList(new Human(100), new Human(199), new Human(89));
        List<Integer> res = new ArrayList<>();
        //imperative style
//        for(Human human : humans){
//            if(human.getWeight() > 90){
//                res.add(human.getWeight());
//            }
//        }
        //stream style
        res = humans.stream().filter((e) -> e.getWeight() > 90).map(e -> e.getWeight()).collect(toList());

        System.out.println(res);
    }

    private static class Human{
        private int weight;
        Human(int weight){
            this.weight = weight;
        }

        public int getWeight(){
            return weight;
        }

        public String toString(){
            return "my weight is: " + weight;
        }
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章