zoukankan      html  css  js  c++  java
  • java笔记:流式编程 数组与List集合互转


    别再用for循环了。借助org.apache.commons.lang.ArrayUtils更优雅! 

    数组转集合:long[]转List<Long>

    import org.apache.commons.lang.ArrayUtils;

    long[] array_long = {1L, 2L, 3L};
    //装箱,把基本类型数组转成对应的包装类数组
    Long[] array_Long = ArrayUtils.toObject(array_long);
    return Arrays.asList(array_Long);

    集合转数组:List<Long>转long[]


    import org.apache.commons.lang.ArrayUtils;
    long[] array_long = ArrayUtils.toPrimitive(array_Long);



    要根据一个List<Entity>,得到entity的id的集合。可以使用流式编程的mapToLong方法;同样如果得到其他数据类型的集合,可以使用mapToDouble、mapToInt等。

    long[] array_long = entList.stream().mapToLong(Enterprise::getEnterpriseId).toArray();

    要对数组做流式编程,可以先通过Arrays.stream(localEnterpriseIdList)将数组转换成Stream对象。


    List<Long>转List<String>

    List<Long> l1 = Arrays.asList(1L, 3L, 2L);
    List<String> strings = l1.stream().map(String::valueOf).collect(Collectors.toList());

     对List<Long>进行排序

    import java.util.Collections;
    Collections.sort(l2);

    将List<Long>里的数字转换成用","分割的字符串 

    List<Long> l1 = Arrays.asList(1L, 3L, 2L);
    String join = String.join(",", l1.stream().map(String::valueOf).toArray(String[]::new));
  • 相关阅读:
    个人任务
    个人任务。。
    个人任务。
    个人任务
    未来周计划(一)
    澡堂人数实时查询助手的NABC分析
    react 中的fragments
    数组
    如何区分对象、数组、null
    数组的并集,交集,差集的实现
  • 原文地址:https://www.cnblogs.com/buguge/p/12712143.html
Copyright © 2011-2022 走看看