java8 Stream

646 阅读8分钟

一、
list转map

Map<Long, B2bCollectOrderContractRelation> maps = collectRelations.stream().collect(Collectors.toMap(B2bCollectOrderContractRelation::getId, Function.identity()));
Map<String, String> currencyMap = currencyListResp.getData().stream().collect(Collectors.toMap(CurrencyEntry::getKey, CurrencyEntry::getVal, (k1, k2) -> k1));
Map<Long, String> maps = collectRelations.stream().collect(Collectors.toMap(B2bCollectOrderContractRelation::getId, B2bCollectOrderContractRelation::getCollectOrderNo));
Map<String, List<B2bCollectOrderContractRelation>> maps = collectRelations.stream().collect(Collectors.groupingBy(B2bCollectOrderContractRelation::getSysContractNo));

list<Object'>转List<String'>

List<String> sysContractNos = associateContracts.stream().map(CollectContractDTOV1::getSysContractNo).collect(Collectors.toList());
Set<String> sysContractNos = associateContracts.stream().map(CollectContractDTOV1::getSysContractNo).collect(Collectors.toSet());

list<Object'>转List<String'> 去重 过滤

List<String> allotIds = collectOrders.stream().map(CollectB2BPageVO::getAllotId).filter(StringUtils::isNotBlank).distinct().collect(Collectors.toList());

List获取第一个元素

GclFundTrack payFundTrack = list.stream().filter(x -> GPINoticeTypeEnum.PAYING_BANK.getCode().equals(x.getInformType())).findFirst().orElse(null);

List获取随机元素

GclFundTrack payFundTrack = list.stream().filter(x -> GPINoticeTypeEnum.PAYING_BANK.getCode().equals(x.getInformType())).findAny().orElse(null);

升序

//时间正序
Collections.sort(recordList, (item1, item2) -> item1.getCreateDate().compareTo(item2.getCreateDate()));
recordList.sort(Comparator.comparing(OrderOperationRecordDTO::getCreateDate));

降序

recordList.sort(Comparator.comparing(OrderOperationRecordDTO::getCreateDate).reversed());

去重

List<B2bCollectOrderContractRelation> collectRelations = new ArrayList<>();
collectRelations.add(new B2bCollectOrderContractRelation("ffa88ed8b2ff4e58bdb6e72d86ec1a40","haha"));
collectRelations.add(new B2bCollectOrderContractRelation("ffa88ed8b2ff4e58bdb6e72d86ec1a40","haha1"));
collectRelations.add(new B2bCollectOrderContractRelation("ffa88ed8b2ff4e58bdb6e72d86ec1a42","haha2"));
collectRelations.add(new B2bCollectOrderContractRelation("ffa88ed8b2ff4e58bdb6e72d86ec1a43","haha3"));
List<B2bCollectOrderContractRelation> distincts = collectRelations.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(()->new TreeSet<>(Comparator.comparing(B2bCollectOrderContractRelation::getSysContractNo))),ArrayList::new));

输出结果

B2bCollectOrderContractRelation("ffa88ed8b2ff4e58bdb6e72d86ec1a40","haha")
B2bCollectOrderContractRelation("ffa88ed8b2ff4e58bdb6e72d86ec1a42","haha2")
B2bCollectOrderContractRelation("ffa88ed8b2ff4e58bdb6e72d86ec1a43","haha3")
//模拟数据
String str = "[{"code":"4","codeType":"ALRAM","sortId":"4","name":"特级告警"},{"code":"2","codeType":"ALRAM","sortId":"2","name":"中级告警"},{"code":"3","codeType":"ALRAM","sortId":"3","name":"严重告警"},{"code":"1","codeType":"ALRAM","sortId":"1","name":"普通告警"},{"code":"2","codeType":"NOTICE","sortId":"2","name":"邮箱通知"},{"code":"1","codeType":"NOTICE","sortId":"1","name":"短信通知"},{"code":"3","codeType":"NOTICE","sortId":"3","name":"微信消息通知"}]";
[{"code":"4","codeType":"ALRAM","sortId":"4","name":"特级告警"},{"code":"2","codeType":"ALRAM","sortId":"2","name":"中级告警"},{"code":"3","codeType":"ALRAM","sortId":"3","name":"严重告警"},{"code":"1","codeType":"ALRAM","sortId":"1","name":"普通告警"},{"code":"2","codeType":"NOTICE","sortId":"2","name":"邮箱通知"},{"code":"1","codeType":"NOTICE","sortId":"1","name":"短信通知"},{"code":"3","codeType":"NOTICE","sortId":"3","name":"微信消息通知"}]
List<CollectAlarmDTO> list = JsonUtil.jsonToObject(str, new TypeReference<List<CollectAlarmDTO>>() {});
Map<String, List<String>> codeTypeNameMap1 = list.stream().collect(Collectors.groupingBy(CollectAlarmDTO::getCodeType, Collectors
                .collectingAndThen(Collectors.toList(), t -> ListUtils.emptyIfNull(t).stream().map(CollectAlarmDTO::getName)
                                .filter(Objects::nonNull).distinct().collect(Collectors.toList()))));
Map<String, List<String>> codeTypeNameMap2 =list.stream().collect(Collectors.groupingBy(CollectAlarmDTO::getCodeType,
                Collectors.mapping(CollectAlarmDTO::getName, Collectors.toList())));
System.out.println(JsonUtil.objectToJson(codeTypeNameMap2));
结果
{
    "NOTICE": ["邮箱通知", "短信通知", "微信消息通知"],
    "ALRAM": ["特级告警", "中级告警", "严重告警", "普通告警"]
}
//模拟数据
String str = "[{"code":"4","codeType":"ALRAM","sortId":"4","name":"特级告警"},{"code":"2","codeType":"ALRAM","sortId":"2","name":"中级告警"},{"code":"3","codeType":"ALRAM","sortId":"3","name":"严重告警"},{"code":"1","codeType":"ALRAM","sortId":"1","name":"普通告警"},{"code":"2","codeType":"NOTICE","sortId":"2","name":"邮箱通知"},{"code":"1","codeType":"NOTICE","sortId":"1","name":"短信通知"},{"code":"3","codeType":"NOTICE","sortId":"3","name":"微信消息通知"}]";
[{"code":"4","codeType":"ALRAM","sortId":"4","name":"特级告警"},
{"code":"2","codeType":"ALRAM","sortId":"2","name":"中级告警"},
{"code":"3","codeType":"ALRAM","sortId":"3","name":"严重告警"},
{"code":"1","codeType":"ALRAM","sortId":"1","name":"普通告警"},
{"code":"2","codeType":"NOTICE","sortId":"2","name":"邮箱通知"},
{"code":"1","codeType":"NOTICE","sortId":"1","name":"短信通知"},
{"code":"3","codeType":"NOTICE","sortId":"3","name":"微信消息通知"}]
List<CollectAlarmDTO> list = JsonUtil.jsonToObject(str, new TypeReference<List<CollectAlarmDTO>>() {
});
Map<String, Map<String, String>> codeTypeMap1 = list.stream().collect(Collectors.groupingBy(CollectAlarmDTO::getCodeType,
        Collectors.collectingAndThen(Collectors.toMap(CollectAlarmDTO::getCode, CollectAlarmDTO::getName, (x, y) -> x), v -> v)));
System.out.println(JsonUtil.objectToJson(codeTypeMap1));
Map<String, Map<String, String>> codeTypeMap2 = list.stream().collect(Collectors.groupingBy(CollectAlarmDTO::getCodeType,
        Collectors.toMap(CollectAlarmDTO::getCode, CollectAlarmDTO::getName, (x, y) -> x)));
System.out.println(JsonUtil.objectToJson(codeTypeMap2));
结果
{
    "NOTICE": {
    "1": "短信通知",
            "2": "邮箱通知",
            "3": "微信消息通知"
},
    "ALRAM": {
    "1": "普通告警",
            "2": "中级告警",
            "3": "严重告警",
            "4": "特级告警"
}
}
//模拟数据
String str = "[{"code":"4","codeType":"ALRAM","sortId":"4","name":"特级告警"},{"code":"2","codeType":"ALRAM","sortId":"2","name":"中级告警"},{"code":"3","codeType":"ALRAM","sortId":"3","name":"严重告警"},{"code":"1","codeType":"ALRAM","sortId":"1","name":"普通告警"},{"code":"2","codeType":"NOTICE","sortId":"2","name":"邮箱通知"},{"code":"1","codeType":"NOTICE","sortId":"1","name":"短信通知"},{"code":"3","codeType":"NOTICE","sortId":"3","name":"微信消息通知"}]";
[{"code":"4","codeType":"ALRAM","sortId":"4","name":"特级告警"},{"code":"2","codeType":"ALRAM","sortId":"2","name":"中级告警"},{"code":"3","codeType":"ALRAM","sortId":"3","name":"严重告警"},{"code":"1","codeType":"ALRAM","sortId":"1","name":"普通告警"},{"code":"2","codeType":"NOTICE","sortId":"2","name":"邮箱通知"},{"code":"1","codeType":"NOTICE","sortId":"1","name":"短信通知"},{"code":"3","codeType":"NOTICE","sortId":"3","name":"微信消息通知"}]
List<CollectAlarmDTO> list = JsonUtil.jsonToObject(str, new TypeReference<List<CollectAlarmDTO>>() {
});

Map<String, CollectAlarmDTO> codeMax = list.stream().collect(Collectors.toMap(CollectAlarmDTO::getCodeType, Function.identity(), BinaryOperator.maxBy(Comparator.comparingInt(f1 -> Integer.parseInt(f1.getCode())))));
Map<String, CollectAlarmDTO> codeMa1x = list.stream().collect(Collectors.groupingBy(CollectAlarmDTO::getCodeType, Collectors.collectingAndThen(Collectors.maxBy(Comparator.comparingInt(f1 -> Integer.parseInt(f1.getCode()))), Optional::get)));
结果
{
    "NOTICE": {
    "code": "3",
            "codeType": "NOTICE",
            "sortId": "3",
            "name": "微信消息通知"
},
    "ALRAM": {
    "code": "4",
            "codeType": "ALRAM",
            "sortId": "4",
            "name": "特级告警"
}
}
//模拟数据
String str = "[{"code":"4","codeType":"ALRAM","sortId":"4","name":"特级告警"},{"code":"2","codeType":"ALRAM","sortId":"2","name":"中级告警"},{"code":"3","codeType":"ALRAM","sortId":"3","name":"严重告警"},{"code":"1","codeType":"ALRAM","sortId":"1","name":"普通告警"},{"code":"2","codeType":"NOTICE","sortId":"2","name":"邮箱通知"},{"code":"1","codeType":"NOTICE","sortId":"1","name":"短信通知"},{"code":"3","codeType":"NOTICE","sortId":"3","name":"微信消息通知"}]";
[{"code":"4","codeType":"ALRAM","sortId":"4","name":"特级告警"},{"code":"2","codeType":"ALRAM","sortId":"2","name":"中级告警"},{"code":"3","codeType":"ALRAM","sortId":"3","name":"严重告警"},{"code":"1","codeType":"ALRAM","sortId":"1","name":"普通告警"},{"code":"2","codeType":"NOTICE","sortId":"2","name":"邮箱通知"},{"code":"1","codeType":"NOTICE","sortId":"1","name":"短信通知"},{"code":"3","codeType":"NOTICE","sortId":"3","name":"微信消息通知"}]
List<CollectAlarmDTO> list = JsonUtil.jsonToObject(str, new TypeReference<List<CollectAlarmDTO>>() {
});
分组后,根据sortId进行排序-正序
Map<String, List<CollectAlarmDTO>> groupAscSort = list.stream().collect(Collectors.groupingBy(CollectAlarmDTO::getCodeType, LinkedHashMap::new, Collectors.collectingAndThen(Collectors.toList(), s -> s.stream().sorted(Comparator.comparing(CollectAlarmDTO::getSortId)).collect(Collectors.toList()))));
System.out.println(JsonUtil.objectToJson(groupAscSort));
{
    "ALRAM": [{
    "code": "1",
            "codeType": "ALRAM",
            "sortId": "1",
            "name": "普通告警"
}, {
    "code": "2",
            "codeType": "ALRAM",
            "sortId": "2",
            "name": "中级告警"
}, {
    "code": "3",
            "codeType": "ALRAM",
            "sortId": "3",
            "name": "严重告警"
}, {
    "code": "4",
            "codeType": "ALRAM",
            "sortId": "4",
            "name": "特级告警"
}],
    "NOTICE": [{
    "code": "1",
            "codeType": "NOTICE",
            "sortId": "1",
            "name": "短信通知"
}, {
    "code": "2",
            "codeType": "NOTICE",
            "sortId": "2",
            "name": "邮箱通知"
}, {
    "code": "3",
            "codeType": "NOTICE",
            "sortId": "3",
            "name": "微信消息通知"
}]
}
//模拟数据
String str = "[{"code":"4","codeType":"ALRAM","sortId":"4","name":"特级告警"},{"code":"2","codeType":"ALRAM","sortId":"2","name":"中级告警"},{"code":"3","codeType":"ALRAM","sortId":"3","name":"严重告警"},{"code":"1","codeType":"ALRAM","sortId":"1","name":"普通告警"},{"code":"2","codeType":"NOTICE","sortId":"2","name":"邮箱通知"},{"code":"1","codeType":"NOTICE","sortId":"1","name":"短信通知"},{"code":"3","codeType":"NOTICE","sortId":"3","name":"微信消息通知"}]";
[{"code":"4","codeType":"ALRAM","sortId":"4","name":"特级告警"},{"code":"2","codeType":"ALRAM","sortId":"2","name":"中级告警"},{"code":"3","codeType":"ALRAM","sortId":"3","name":"严重告警"},{"code":"1","codeType":"ALRAM","sortId":"1","name":"普通告警"},{"code":"2","codeType":"NOTICE","sortId":"2","name":"邮箱通知"},{"code":"1","codeType":"NOTICE","sortId":"1","name":"短信通知"},{"code":"3","codeType":"NOTICE","sortId":"3","name":"微信消息通知"}]
List<CollectAlarmDTO> list = JsonUtil.jsonToObject(str, new TypeReference<List<CollectAlarmDTO>>() {
});
分组后,根据sortId进行排序-反序
Map<String, List<CollectAlarmDTO>> groupReverseSort = list.stream().collect(Collectors.groupingBy(CollectAlarmDTO::getCodeType, LinkedHashMap::new, Collectors.collectingAndThen(Collectors.toList(), s -> s.stream().sorted((c1, c2) -> c2.getSortId().compareTo(c1.getSortId())).collect(Collectors.toList()))));
System.out.println(JsonUtil.objectToJson(groupReverseSort));
{
    "ALRAM": [{
    "code": "4",
            "codeType": "ALRAM",
            "sortId": "4",
            "name": "特级告警"
}, {
    "code": "3",
            "codeType": "ALRAM",
            "sortId": "3",
            "name": "严重告警"
}, {
    "code": "2",
            "codeType": "ALRAM",
            "sortId": "2",
            "name": "中级告警"
}, {
    "code": "1",
            "codeType": "ALRAM",
            "sortId": "1",
            "name": "普通告警"
}],
    "NOTICE": [{
    "code": "3",
            "codeType": "NOTICE",
            "sortId": "3",
            "name": "微信消息通知"
}, {
    "code": "2",
            "codeType": "NOTICE",
            "sortId": "2",
            "name": "邮箱通知"
}, {
    "code": "1",
            "codeType": "NOTICE",
            "sortId": "1",
            "name": "短信通知"
}]
}
//HashSet去重(无序)->利用HashSet去重,只需要重写其equals()和hashCode()方法
List<Integer>list = Stream.of(1,3,5,2,1,3,7,2).collect(Collectors.toList());
HashSet<Integer> set = new HashSet<>(list);
List<Integer> list2= list.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(HashSet::new),ArrayList::new));
元集合[1,3,5,2,1,3,7,2]
去重集合[1,2,3,5,7]

//LinkedHashSet去重(有序)
LinkedHashSet<Integer> set1 = new LinkedHashSet<>(list);
元集合[1,3,5,2,1,3,7,2]
去重集合[1,3,5,2,7]

//TreeSet去重(无序)
TreeSet<Integer> set3 = new TreeSet<>(list);
元集合[1,3,5,2,1,3,7,2]
去重集合[1,2,3,5,7]

//distinct去重
list = list.stream().distinct().collect(Collectors.toList());
元集合[1,3,5,2,1,3,7,2]
去重集合[1,3,5,2,7]
List<B2bCollectOrderContractRelation> collectRelations = new ArrayList<>();
// summingInt 求年龄总和
IntSummaryStatistics collect1 = collectRelations.stream().collect(Collectors.summarizingInt(B2bCollectOrderContractRelation::getInputAmount));
DoubleSummaryStatistics collect2 = collectRelations.stream().collect(Collectors.summarizingDouble(B2bCollectOrderContractRelation::getInputAmount));
LongSummaryStatistics collect3 = collectRelations.stream().collect(Collectors.summarizingLong(B2bCollectOrderContractRelation::getInputAmount));

// 年龄总和
System.out.println(collect1.getSum());
// 年龄平均值
System.out.println(collect1.getAverage());
// 统计数量
System.out.println(collect1.getCount());
// 年龄总和
System.out.println(collect2.getSum());
// 年龄平均值
System.out.println(collect2.getAverage());
// 统计数量
System.out.println(collect2.getCount());
// 年龄总和
System.out.println(collect3.getSum());
// 年龄平均值
System.out.println(collect3.getAverage());
// 统计数量
System.out.println(collect3.getCount());

BigDecimal inputAmountSum = collectRelations.stream()
        .map(B2bCollectOrderContractRelation::getInputAmount)
        .reduce(BigDecimal.ZERO, BigDecimal::add);
List<B2bCollectOrderContractRelation> collectRelations = new ArrayList<>();
// summingInt 求年龄总和
IntSummaryStatistics collect1 = collectRelations.stream().collect(Collectors.summarizingInt(B2bCollectOrderContractRelation::getInputAmount));
DoubleSummaryStatistics collect2 = collectRelations.stream().collect(Collectors.summarizingDouble(B2bCollectOrderContractRelation::getInputAmount));
LongSummaryStatistics collect3 = collectRelations.stream().collect(Collectors.summarizingLong(B2bCollectOrderContractRelation::getInputAmount));

// 年龄总和
System.out.println(collect1.getSum());
// 年龄平均值
System.out.println(collect1.getAverage());
// 统计数量
System.out.println(collect1.getCount());
// 年龄总和
System.out.println(collect2.getSum());
// 年龄平均值
System.out.println(collect2.getAverage());
// 统计数量
System.out.println(collect2.getCount());
// 年龄总和
System.out.println(collect3.getSum());
// 年龄平均值
System.out.println(collect3.getAverage());
// 统计数量
System.out.println(collect3.getCount());

BigDecimal inputAmountSum = collectRelations.stream()
        .map(B2bCollectOrderContractRelation::getInputAmount)
        .reduce(BigDecimal.ZERO, BigDecimal::add);

//filter方法
Stream<String> stream = Stream.of("zdy", "zyz", "cyx", "mcs");
stream.filter(s -> s.contains("z")) // 包含"z"的留下
        .filter(s -> s.contains("y")) // 包含"y"的留下
        .forEach(System.out::println); // 打印 "zdy" "zyz"
//limit方法
Stream<String> stream = Stream.of("zdy", "zyz", "cyx", "mcs");
stream.limit(2).forEach(System.out::println); // 打印 "zdy" "zyz"
//skip方法
Stream<String> stream = Stream.of("zdy", "zyz", "cyx", "mcs");
stream.skip(2).forEach(System.out::println); // 打印 "cyx" "mcs"
//match方法
Stream<Integer> stream = Stream.of(5, 2, 7, 4);
boolean match = stream.allMatch(num -> num > 4); // 所有数据都>4吗
System.out.println(match); // 打印 "false"

Stream<Integer> stream2 = Stream.of(5, 2, 7, 4);
boolean anyMatch = stream2.anyMatch(num -> num > 4); // 有数据>4吗
System.out.println(anyMatch); // 打印 "true"

Stream<Integer> stream3 = Stream.of(5, 2, 7, 4);
boolean noneMatch = stream3.noneMatch(num -> num == 3); // 没有数据=3吗
//max方法
Stream<Integer> stream = Stream.of(5, 2, 7, 4);
Integer max = stream.max((num1, num2) -> num1 - num2).orElse(null);
//min方法
Stream<Integer> stream = Stream.of(5, 2, 7, 4);
Integer min = stream.min((num1, num2) -> num1 - num2).orElse(null);
//合并
Stream<String> stream1 = Stream.of("zdy", "zyz", "cyx", "mcs");
Stream<Integer> stream2 = Stream.of(5, 2, 7, 4);
Stream<? extends Serializable> stream = Stream.concat(stream1, stream2);

Stream<String> stream1 = Stream.of("zdy", "zyz", "cyx", "mcs");
// 保存到Set中
Set<String> collect = stream1.collect(Collectors.toSet());
// 保存到List中
List<String> collect1 = stream1.collect(Collectors.toList());
// 保存到ArrayList
ArrayList<String> collect2 = stream1.collect(Collectors.toCollection(ArrayList::new));
// 保存到ArraySet
HashSet<String> collect3 = stream1.collect(Collectors.toCollection(HashSet::new));
Stream<Person> stream = Stream.of(new Person("zdy", 23),
        new Person("zyz", 24),
        new Person("cyx", 25),
        new Person("mcs", 26));
// maxBy 获取年龄最大值 minBy 获取最小值
Optional<Person> collect = stream.collect(Collectors.maxBy((p1, p2) -> p1.getAge() - p2.getAge()));
Stream<Person> stream2 = Stream.of(new Person("zdy", 21),
        new Person("zyz", 22),
        new Person("cyx", 25),
        new Person("mcs", 24));
// 根据三个字符进行拼接 三个字符串分别为分隔符、前缀、后缀
String collect1 = stream2.map(Person::getName).collect(Collectors.joining("_", "@", "^"));
// 打印 👇
// @zdy_zyz_cyx_mcs^
//allMatch所有数据都满足条件,anyMatch任意一条数据满足条件,noneMatch没有数据满足条件,都返回boolean类型
Stream<Integer> stream = Stream.of(5, 2, 7, 4);
boolean match = stream.allMatch(num -> num > 4); // 所有数据都>4吗
System.out.println(match); // 打印 "false"

Stream<Integer> stream2 = Stream.of(5, 2, 7, 4);
boolean anyMatch = stream2.anyMatch(num -> num > 4); // 有数据>4吗
System.out.println(anyMatch); // 打印 "true"

Stream<Integer> stream3 = Stream.of(5, 2, 7, 4);
boolean noneMatch = stream3.noneMatch(num -> num == 3); // 没有数据=3吗
System.out.println(noneMatch); // 打印 "true"