Java8函数式编程

时间:2021-04-19 19:00:05

1、什么是函数式编程?

函数式编程的核心是:在思考问题时,使用不可变值和函数,函数对一个值进行处理,映射成另一个值。

2、Lambda表达式的学习

要点:Lambda表达式是一个匿名方法,将行为像数据一样传递,常见结构如下:BinaryOperator<Integer> add = (x,y)->x+y。

3、流:常见的流操作

3.1、collect(toList())

 //及早求值方法
 long count = artists.stream().filter(a->a.isFrom("china")).count();
 long count2 = artists.stream().filter(b->b.getName().equals("TTG")).count();
 long count3 = artists.stream()
      .filter(a->{
        System.out.println(a.getName());
        return a.isFrom("china");
      })
      .count();

 

List<String> collected = Stream.of("a","b","c").collect(Collectors.toList());
String collectedStr = JSONArray.toJSONString(collected);
boolean isequal = collected.equals(Arrays.asList("a","b","c"));

3.2、map

        //2.map
        List<String> str = Stream.of("a","b","c")
                .map(s -> s.toUpperCase())
                .collect(Collectors.toList());
        String realStr = JSONArray.toJSONString(str);
        boolean isSame = realStr.equals(Arrays.asList("A","B","C"));

3.3、filter

        //3.filter
        List<Object> str2 = Stream.of("abc","1abc","abc1")
                .filter(s -> isDight(s.charAt(0)))
                .collect(Collectors.toList());
        String rStr2 = JSONArray.toJSONString(str2);

3.4、flatMap

 //flatMap:flatMap 方法可用 Stream 替换值,然后将多个 Stream 连接成一个 Stream
 List<String> str3 = Stream.of(Arrays.asList("a","b","c"),Arrays.asList("d","e"))
                .flatMap(stringList -> stringList.stream())
                .collect(Collectors.toList());
  String rStr3 = JSONArray.toJSONString(str3);

3.5、max和min

//max min
List<Track> tracks = Arrays.asList(new Track("Bakai", 524),
    new Track("Violets for Your Furs", 378),
    new Track("Time Was", 451));
Track shortTrack =             
    tracks.stream().min(Comparator.comparing(track>track.getLength()))
    .get();

3.6、整合+通用模式

  //reduce
        //1.累加
        int count4 = Stream.of(1,2,3)
                .reduce(0,(acc,res)->acc+res);

        //整合
        Album album = null;
        Set<String> orgin = album.getMusicians()
                .filter(artist -> artist.getName().startsWith("The"))
                .map(artist -> artist.getNationality())
                .collect(Collectors.toSet());
        System.out.println(count4);

        int totalMembers = 0;
        for (Artist artist : artists) {
            Stream<Artist> members = artist.getMembers();
            totalMembers += members.count();
        }

    }