java常用数据转换

发布于:2025-03-21 ⋅ 阅读:(39) ⋅ 点赞:(0)

1.   List与数组互转
    ArrayList<String> list = new ArrayList<>();
    String[] array = list.stream().toArray(String[]::new);


    String[] array1 = {"apple", "banana", "orange"};
    List<String> list1 = Arrays.stream(array1).collect(Collectors.toList());

    String[] cateArray = cateList.toArray(new String[cateList.size()]);

2.new集合对像
    import com.google.common.collect.Lists;
    import com.google.common.collect.Maps;
    List<String> arrayList = Lists.newArrayList();
    Map<String, Object[]> concurrentMap = Maps.newConcurrentMap();
    Map<String, Object> resultMap = Maps.newHashMap();

3.集合转字符串

   例1:List<String> attachListFar = new ArrayList<>();
       attachListFar.add(attachDto.getFilePath());
    String attachListFarStr = String.join(",", attachListFar);

例2:if (StringUtils.isNotBlank(approvedBy)) {
    StringJoiner userStrJoin = new StringJoiner(",");
    String[] userIds = approvedBy.split(",");
    for (String uId : userIds) {
        String com = RedisUtil.getName(RedisConstant.SYS_DEPT_USER_ID, uId);
        userStrJoin.add(com);
    }
    outDto.setApprovedByName(userStrJoin.toString());//多人名字
}

    4.stream集合变换:
    //list对象
    List<String> idList= todoViewList.stream().map(HdInfoTodoView::getId).collect(Collectors.toList());
    dto.setHdIds(listWithoutRepeat.toArray(new String[listWithoutRepeat.size()]));
    Map<String, List<SafetyInspectRecordDetail>> map = list.stream().collect(Collectors.groupingBy(SafetyInspectRecordDetail::getInspectRecordId));
   //map对象
Map<String, String> levelMap = inspectLevelResult.getData() == null ? Maps.newConcurrentMap() : inspectLevelResult.getData().stream().collect(Collectors.toMap(SysDictDataOutDto::getDictValue, SysDictDataOutDto::getDictLabel, (k, v) -> v));
    
    //map对象
    Map<String, HdInfoOutDto> hdMap = list.stream().collect(Collectors.toMap(HdInfoOutDto::getId, p -> p, (k, v) -> v));
                
    // 去重
     List<String> userNameList = list.stream().filter(c -> MyStringUtil.isNotEmpty(c.getUserName())).map(CisAlarm::getUserName).distinct().collect(Collectors.toList());