美文网首页
【JAVA】Lambda使用

【JAVA】Lambda使用

作者: Y了个J | 来源:发表于2019-08-23 14:49 被阅读0次

    List转Map

    public Map<Long, String> getIdNameMap(List<Account> accounts) {
        return accounts.stream().collect(Collectors.toMap(Account::getId, Account::getUsername));
    }
    
    public Map<Long, Account> getIdAccountMap(List<Account> accounts) {
        return accounts.stream().collect(Collectors.toMap(Account::getId, account -> account));
    }
    

    排序

    crowdList.sort((Comparator.comparing(o -> Optional.ofNullable(o.getSumData()).map(SumDataDTO::getCharge).orElse(0.0))));
    
    crowdList = crowdList.stream().sorted((Comparator.comparing(o -> 
        Optional.ofNullable(o.getSumData()).map(SumDataDTO::getCharge).orElse(0.0)))
    ).collect(Collectors.toList());
    
    public static void main(String[] args) {
            List<Long> listA = Lists.newArrayList(1L, 2L, 3L, 4L);
            List<Long> listB = Lists.newArrayList(1L, 2L, 6L, 8L);
            //取两数组的交集
            List<Long> result = listB.stream().filter(listA::contains).distinct().collect(Collectors.toList());
            System.out.println(result);
        }
    
    
    
    按某个属性进行分组
    Map<Long, List<AsAdgroupCrowdDataHis>> crowDatasMap = dataHisList.stream().collect(Collectors.groupingBy(AsAdgroupCrowdDataHis::getCrowdid));
    
    
    提取对象某个属性
    List<String> stringList = keywordList.stream().map(SubwaysAlgorithmDeleteKeyword::getWord).distinct().collect(Collectors.toList());
    
    //对象数组按coverage倒序排序
    apiHotWordList = apiHotWordList.stream().sorted(Comparator.comparing(ApiKeyWord::getCoverage).reversed()).collect(Collectors.toList());
    
    public static void main(String[] args) {
            List<Long> listA = Lists.newArrayList(1L, 2L, 3L, 4L, 2L, 1L);
            //倒序
            listA.sort(Collections.reverseOrder());
            System.out.println(listA);
            //正序
            Collections.sort(listA);
            System.out.println(listA);
        }
    
    
    public static void main(String[] args) {
            TestVO vo1 = new TestVO();
            vo1.setId(1L);
            vo1.setNum(2);
    
            TestVO vo2 = new TestVO();
            vo2.setId(1L);
            vo2.setNum(1);
    
            List<TestVO> list = new ArrayList<>();
            list.add(vo1);
            list.add(vo2);
    
            //汇总数组对象某个属性的和
            Integer num = list.stream().mapToInt(TestVO::getNum).sum();
            System.out.println(num);//3
            
            Map<Long, Integer> map = list.stream().collect(Collectors.groupingBy(TestVO::getId, Collectors.summingInt(TestVO::getNum)));
            System.out.println(map);
        }
    

    相关文章

      网友评论

          本文标题:【JAVA】Lambda使用

          本文链接:https://www.haomeiwen.com/subject/qceulctx.html