Java8之List转换

  • List转换成map
    public static void listConversionToMap(List list) {
        //颜色作为key,重量作为value,如果key重复,取较重的值(注意:key重复不做处理会报-->java.lang.IllegalStateException: Duplicate key)
        Map colorForWeight = list.stream().collect(Collectors.toMap(Orange::getColor,
                Orange::getWeight, (oldValue, newValue) -> oldValue > newValue ? oldValue : newValue));
    
        //颜色作为key,Orange为value
        Map colorForOrange = list.stream().collect(Collectors.toMap(Orange::getColor,
                (orange) -> orange, (oldValue, newValue) -> oldValue.getWeight() > newValue.getWeight() ? oldValue :
                        newValue));
    
        //已颜色作为key进行分组
        Map> colorForOranges = list.stream().collect(Collectors.groupingBy(Orange::getColor));
    }
    
  • List转换成Set
    public static void listConversionToSet(List list) {
        list.stream().collect(Collectors.toSet());
    }
    
    //将实体中的某属性转换为set
    public static void listConversionToSet(List list) {
        Set colorSet = list.stream().map((orange) -> orange.getColor()).collect(Collectors.toSet());
    }
    

更多文章:
CSDN博客
简书博客
公众号:代码小搬运
代码小搬运.jpg

你可能感兴趣的:(Java开发,#,Java8,java8,list)