• 关于Java8 Stream的简单实用记录


    Java8 stream的使用
    1、集合对象取某个属性形成集合
    List<String> knows = examPaperList.stream().map(TestExam::getKnowPoint).collect(Collectors.toList());
    2、统计上述String的个数形成Map
    Map<String, Long> mapKnow = knows.stream().collect(groupingBy(p -> p,Collectors.counting()));
    3、集合对象去重累加形成Map
    Map<String, Double> resultFull = examPaperList.stream().collect(Collectors.toMap( TestExam::getKnowPoint, TestExam::getFullScore,(v1,v2)->{ return v1+v2;} ));
    4、Map遍历新方法(遍历上述map):
    resultFull.foreach((k,v)->{Systeam.out.println("key:"+k+"value:"+v)});
    5、把集合中按照某个属性分成多个集合
    List<SubjectToStudent> testSubjectList = wangYueTestMapper.queryTestSubjectOther(projectId,subject);
    testSubjectList.stream().collect(Collectors.groupingBy(SubjectToStudent::getSubject,Collectors.toList()))
    .forEach((subjects,fooListByAge)->{
    groupList.add(fooListByAge);
    });
    6、集合差集
    list=list1.stream().filter(t-> !list2.contains(t)).collect(Collectors.toList());
    7、集合交集
    List<Integer> list=list1.stream().filter(t->list2.contains(t)).collect(Collectors.toList());
    8、统计集合重复元素出现次数,并且去重返回hashmap
    Map<String, Long> map = list.stream().
    collect(Collectors.groupingBy(Function.identity(),Collectors.counting()));
    System.out.println(map);
    9、由于hashmap无序,所以在排序放入LinkedHashMap里(key升序)
    Map<String, Long> sortMap = new LinkedHashMap<>();
    map.entrySet().stream().sorted(Map.Entry.comparingByKey()).
    forEachOrdered(e -> sortMap.put(e.getKey(), e.getValue()));
    System.out.println(sortMap);
    10、获取排序后map的key集合
    List<String> keys = new LinkedList<>();
    sortMap.entrySet().stream().forEachOrdered(e -> keys.add(e.getKey()));
    System.out.println(keys);
    11、获取排序后map的value集合
    List<Long> values = new LinkedList<>();
    sortMap.entrySet().stream().forEachOrdered(e -> values.add(e.getValue()));
    System.out.println(values);
    12、集合某属性求和
    Double sum = investorList.stream().mapToDouble(n -> CommonUtils.isNumeric(n.getInvestMoney()) ?
    Double.parseDouble(n.getInvestMoney()) : 0.00).summaryStatistics().getSum();
    13、集合按属性降序输出(升序去掉reversed()方法)
    List<TestListOut> newList = unique.stream().sorted(Comparator.comparing(TestListOut::getPublishTime).reversed())
    .collect(Collectors.toList());

  • 相关阅读:
    hdu 5053 the Sum of Cube
    [LeetCode] Word Pattern
    [LeetCode] Minimum Depth of Binary Tree
    [C++] std::vector
    [LeetCode] Count Binary Substrings
    [LeetCode] Degree of an Array
    [LeetCode] String to Integer (atoi)
    [LintCode] 比较字符串
    [LeetCode] Valid Parentheses
    [LeetCode] Perfect Number
  • 原文地址:https://www.cnblogs.com/pandazhao/p/11739301.html
Copyright © 2020-2023  润新知