java8常用lambda表达式及Stream()常用方法简单例子<List;Map;String之间转换及流map;peck;filter>

1,275 阅读4分钟
package cn.asae.e.niceutil.utilobject;

import com.google.common.collect.Maps;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.junit.Test;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @Description 集合常用方法(java 8)
 * @Author nice
 * @Date 2021/5/19 2:07Z 下午
 */
public class Collect {

    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    class Nice {
        String name;
        NceDel niceDel;
        Integer num;
    }

    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    class NceDel {
        String name;
        Nice nice;
        List<Nice> niceList;
    }

    private static final Map<String, String> map = new HashMap();
    private static List<Nice> list = new ArrayList<>();

    static {
        map.put("nice1", "11111");
        map.put("nice2", "22222");
    }

    /**
     * 使用 Optional 空对象,然后再次判定
     */
    @Test
    public void test1() {
        Nice niceText = new Nice();
        niceText.setName("nice");
        niceText.setNiceDel(null);
        Nice nice = Optional.ofNullable(niceText).filter(s -> s.getName() == null).map(c -> c.getNiceDel()).map(d -> d.getNice()).orElse(null);
        if (nice == null) {
            System.out.println("空判定");
        }
    }

    /**
     * List 转为 String  Map 转为 String
     */
    @Test
    public void test2() {
        List<String> list1 = Arrays.asList("文学", "小说", "历史", "言情", "科幻", "悬疑");
        List<String> listNull = null;
        //方案一:使用String.join()函数,(java)
        String string1 = String.join(",", list1);

        System.out.println(string1);
        //方案二:采用流的方式来写 (java8)
        String string2 = list1.stream().collect(Collectors.joining("-"));
        System.out.println(string2);

        //String string11 = String.join(",",listNull);  /** 空指针异常 */
        //String string22 = listNull.stream().collect(Collectors.joining("-")); /** 空指针异常 */


        System.out.println(getMapToString(map, "#", ","));
        /** java 8 map 转为list*/
        System.out.println(mapToString(map, "#", ","));
        Object o = null;
    }

    /**
     * java8 list 转为 map 2种方式
     */
    @Test
    public void test3() {
        Nice nice = new Nice();
        nice.setName("hahaha");
        Nice nice1 = new Nice();
        nice1.setName("hahaha");
        list.add(nice);
        list.add(nice1);

        /** 第一种 对象 lambda 表达式 (需要注意:map的key 重复,会抛异常)*/
        list.stream().collect(Collectors.toMap(Nice::getName, a -> a));
        /** 第一种 另外写法 Function接口中的一个默认方法代替 也会抛key异常*/
        list.stream().collect(Collectors.toMap(Nice::getName, Function.identity()));

        /** 重复key 解决办法*/
        list.stream().collect(Collectors.toMap(Nice::getName, Function.identity(), (val1, val2) -> val2));
        /** 重复key 解决办法 重载方法,可以指定一个Map的具体实现 */
        list.stream().collect(Collectors.toMap(Nice::getName, Function.identity(), (val1, val2) -> val2, LinkedHashMap::new));
        /** 细节解析 */
        ```
        list.stream()
        .collect(Collectors.toMap(Nice::getName,
                Function.identity()
                , (val1, val2) ->  {
                    if(val1.getIssueDate().compareTo(val2.getIssueDate()) > 0){
                        return val1;
                    }
                    return val2;
                }));

        /** 另外一种办法 分组,这样可以避免key 异常 ,不过返回的是List集合*/
        Map<String, List<Nice>> mapNice = list.stream().collect(Collectors.groupingBy(Nice::getName));

        /** 根据集合 分组,并且获取 固定的字段*/
        Map<String,List<String>> map = list.stream().collect(Collectors.groupingBy(Nice::getName,Collectors.mapping(Nice::getName, Collectors.toList())));

        /** 根据集合 分组,并且获取 分组的 sum值*/
        Map<String,Integer> map1 = list.stream().collect(Collectors.groupingBy(Nice::getName, Collectors.summingInt(Nice::getNum)));
        
        /** 另外的  */
           Map<WarningInfoTypeEnum,Map<String,List<CertificateInfoVo>>> map = Optional.ofNullable(certificateInfoVoList)  
        .orElse(Lists.newArrayList())  
        .stream()  
        .collect(Collectors.groupingBy(CertificateInfoVo::getCertificateLabel,  
        Collectors.groupingBy(CertificateInfoVo::getCertificateOneLabel)));
       
        System.out.println(mapNice.toString());
    }

    /**
     * java8 map 转为 List 2种方式
     */
    @Test
    public void test4() {
        /** 第一种 获取 各自的key和value 组装*/
        List<String> resultValue = map.values().stream()
                .collect(Collectors.toList());
        List<String> resultKey = map.keySet().stream()
                .collect(Collectors.toList());
        /** 第二种直接获取对应list */
        map.entrySet().stream()
                .map(x -> x.getValue())
                .collect(Collectors.toList()).forEach(System.out::println);
    }
    @Test
    public void test11() {
        /** 第一种 获取 各自的key和value 组装*/
       Map<String,Object> map = Maps.newHashMap();
        System.out.println(map.getOrDefault(null,"1"));
    }
    /**
     * java8 去重复
     */
    @Test
    public void test5() {
        Nice nice = new Nice();
        nice.setName("hahaha");
        Nice nice1 = new Nice();
        nice1.setName("hahaha");
        list.add(nice);
        list.add(nice1);
        /** 使用去重复函数 distinct */
        list.parallelStream().distinct().forEach(System.out::println);  /** 使用parallelStream,除非微服务,其他不太推荐。线程all in  */

        /** 根据某个字段 去重复 set */
        /**(一个线程安全;一个不安全)
         * 1、ArrayList是Array的数据结构,而LinkedList是Link的数据结构;
         * 2、随机访问时,ArrayList优于LinkedList;
         * 3、新增和删除操作,LinedList比较占优势 */
        List<Nice> listNew1 = list.stream().collect(
                Collectors.collectingAndThen(Collectors.toCollection(() ->
                        new TreeSet<>(Comparator.comparing(user -> user.getName()+ user.getSex()))), LinkedList::new));


        System.out.println(listNew1.toString());
        /** 验证是否重复 anyMatch */
        boolean b = list.stream().anyMatch(u -> u.getName().equals("Nice"));
        System.out.println(b);
    }

    /**
     * map faltMap filter peck 简单说明和使用
     */
    @Test
    public void test6() {
        Nice nice = new Nice();
        nice.setName("hahaha");
        nice.setNum(1);
        nice.setNiceDel(new NceDel());
        Nice nice1 = new Nice();
        nice1.setName("hahaha");
        nice1.setNum(2);
        Nice nice2 = new Nice();
        nice2.setName("hahaha");
        nice2.setNum(3);
        list.add(nice);
        list.add(nice1);
        list.add(nice2);

        Map<String,Integer> map = list.stream().collect(Collectors.toMap(Nice::getName,Nice::getNum,(v1,v2)->{
            return v1+v2;
        }));

        map.computeIfAbsent("hahah",a-> 21);

        //Integer max = list.stream().max(Comparator.comparingInt(Nice::getNum)).orElse(new Nice()).getNum();
        //System.out.println(max);
        map.forEach((k,v)->{
            System.out.println(k);
            System.out.println(v);
        });

        /** 过滤 filter */
        /** map 一对一进行转换 ; peck 改变对象内容*/
        list.stream().filter(s -> s.getNiceDel() != null)/** 过滤 掉NiceDel不等于空的对象 */
                .map(s -> s.getNiceDel())   /** 返回 NiceDel 结果;等于 s->{ return s.getNiceDel();} 结果集已经变为List<NiceDel> */
                .peek(s -> s.setName("111"))  /** 无返回处理NiceDel中name的值  */
                .collect(Collectors.toList())    /** 返回结果 */
                .forEach(System.out::println);    /** 不行就打印看看 阿们 */
        List<NceDel> listFaltMap = new ArrayList<>();
        NceDel nceDel = new NceDel();
        nceDel.setNiceList(list);
        listFaltMap.add(nceDel);

        /** faltMap 单一转换也可以一对多/多对多转换 */
        listFaltMap.stream()
                .flatMap(s -> s.getNiceList().stream())  /** 多对多转换 */
                .collect(Collectors.toList())
                .forEach(System.out::println);
    }

    /**
     * java8 获取最大值与最小值 及 求和
     */
    public void test7() {
        list.stream().map(s -> s.getNum()).reduce(Integer::max);  /** 最大值 根据 Interger 对象 max */
        list.stream().map(s -> s.getNum()).reduce(Integer::min);  /** 最小值 根据 Interger 对象 max */
        
        String shipDateMin = Collections.min(shipDateList);  
        String shipDateMax = Collections.max(shipDateList);
        
        list.stream().map(s -> s.getNum()).reduce(Integer::sum);  /** 求和*/       
        list.stream().map(Person::getWeight)
                                .reduce(BigDecimal.ZERO, BigDecimal::add);/** BigDecimal 求和*/
    }

    /**
     * java8 排序
     */
    public void test8() {
        /** 根据name 倒序<reversed>,顺序<去掉> */
        list.stream().sorted(Comparator.comparing(Nice::getName).reversed()).limit(3).collect(Collectors.toList());
        
       
     // 先按a倒序排列、再按b倒序排列、最后按c正序排列
    list.sort(Comparator.comparing(SortTest::getA, Comparator.reverseOrder())
            .thenComparing(SortTest::getB, Comparator.reverseOrder())
            .thenComparing(SortTest::getC));
        
    }

    /**
     * 非java8 map 转为String <map,"map间隔符","key:value间隔符"> (有序)
     */
    public static String getMapToString(Map map, String separator, String kvSplice) {
        Set<String> keySet = map.keySet();
        //将set集合转换为数组
        String[] keyArray = keySet.toArray(new String[keySet.size()]);
        //给数组排序(升序)
        Arrays.sort(keyArray);
        //因为String拼接效率会很低的,所以转用StringBuilder。String与StringBuilder
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < keyArray.length; i++) {
            // 参数值为空,则不参与签名 这个方法trim()是去空格
            if (map.get(keyArray[i]) != null) {
                sb.append(keyArray[i]).append(kvSplice).append(map.get(keyArray[i]).toString());
            }
            if (i != keyArray.length - 1) {
                sb.append(separator);
            }
        }
        return sb.toString();
    }

    /**
     * java8(reduce) map转为String <map,"map间隔符","key:value间隔符">  (无序的)
     */
    public static String mapToString(Map<?, ?> map, String separator, String kvSplice) {
        List<String> result = new ArrayList<>();
        map.entrySet().parallelStream().reduce(result, (first, second) -> {
            first.add(second.getKey() + kvSplice + second.getValue());
            return first;
        }, (first, second) -> {
            if (first == second) {
                return first;
            }
            first.addAll(second);
            return first;
        });
        return result.stream().collect(Collectors.joining(separator));
    }

}
    new DecimalFormat("0000000").format(1);
    new DecimalFormat("0000000").format(2);
    new DecimalFormat("0000000").format(3);
    // 0000001
    // 0000002
    // 0000003

试试?

898f09826acddc946ddbcfad4604f95.jpg

学习推荐一个: juejin.cn/post/706475…