Java Lambda 常用语法示例

部分原文

users.stream().forEach(
    item -> System.out.println(item.getId())
);

Optional optional = users.stream().filter(
    item -> item.getId().equals("1")
).findFirst();

//提取对象属性为list
Set papiIds = queueList.stream().map(QueueEntity::getItemId).collect(Collectors.toSet());

//过滤
List collect= users.stream().filter(
    item -> item.getId().equals("1")
).collect(Collectors.toList());

Set newUris = list.stream().filter(m -> {
              String flags = m.get("flags");
                if (!m.isEmpty() && !flags.contains("disconnected") && !flags.contains("s_down")) {
                    return true;
                }
                return false;
            }).map(m -> {
                String ip = m.get("ip");
                String port = m.get("port");
                return convert(ip, port);
            }).collect(Collectors.toSet());

//分组
Map> collect = users.stream().collect(
    Collectors.groupingBy(c -> c.getSex())
);

//排序
users.sort((User o1, User o2) -> o1.getAge().compareTo(o2.getAge()));

//list -> string
String appCodes = packageList.stream().map(item -> item.getCode()).collect(Collectors.joining(","));

//list -> map
Map userMap= users.stream().collect(
        Collectors.toMap((key -> key.getId()), (value -> value))
);

Map propMap = users.stream().collect(
       Collectors.toMap(User::getId, User::getName)
);

//map reduce
Optional reduce = users.stream().map(User::getAge).reduce((i, j) -> i + j);


//去重
String[] words = new String[]{"Hello","World"};
List a = Arrays.stream(words)
        .map(word -> word.split(""))
        .flatMap(Arrays::stream)
        .distinct()
        .collect(toList());
a.forEach(System.out::print);

你可能感兴趣的:(Java Lambda 常用语法示例)