Lambda的使用

常用Lambda处理

  • List to Map
  • Map to List
  • Map to List
  • List to List
  • List排序
  • filter
  • map修改dto的值
  • foreach
  • sort
  • list跟据某个字段去重
  • list to map(key&value多个字段,防止duplicate key)

范例

public class MyLambdaTest {
    public static void main(String[] args) {

        List userDtoList = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            UserDto userDto = new UserDto();
            userDto.setId((long) i);
            userDto.setUserName("name" + i);
            userDto.setAge(10 + i);
            userDtoList.add(userDto);
        }

        //List  to  Map
        Map userDtoMap = userDtoList.stream().collect(Collectors.toMap(UserDto::getId, Function.identity()));

        //Map  to  List
        List map2List = new ArrayList(userDtoMap.values());

        //Map  to  List
        List map2keys = new ArrayList(userDtoMap.keySet());

        //List  to  List
        List userIds = userDtoList.stream().map(UserDto::getId).collect(Collectors.toList());

        //list排序
        userDtoList.sort(Comparator.comparing(UserDto::getUserName)); //按名字排序
        userDtoList.sort((p1, p2) -> {
            return p1.getUserName().toLowerCase().compareTo(p2.getUserName().toLowerCase());
        });

        userDtoList.sort(Comparator.comparing(p -> p.getUserName().toLowerCase()));//lambda表达式

        //filter
        List filterResult = userDtoList.stream().filter(p -> StringUtils.equals(p.getUserName(), "name3")).collect(Collectors.toList());

        //map的使用
        //map函数的主要功能是对List中的每个元素进行处理并返回,可以返回其它的数据类型
        //1.修改dto的值;
        List userDtos = userDtoList.stream().map(userDto -> {
            userDto.setAge(100);
            return userDto;
        }).collect(Collectors.toList());

        //foreach
        userDtoList.stream().forEach(userDto -> {
            userDto.setAge(90);
        });
    }
}
    //排序
    Comparator comparator = (WalletDto d1, WalletDto d2) -> d1.getSortFlag().compareTo(d2.getSortFlag());
    Collections.sort(walletDtoList, comparator);

  //list去重
  unique = symbolContrasts.stream().collect(
                        Collectors.collectingAndThen(Collectors.toCollection(
                                () -> new TreeSet<>(Comparator.comparing(o -> o.getExchange()))), ArrayList::new)
                );

  //list to map(key&value多个字段,防止duplicate key)
resMap = symbolContrasts.stream()
                        .distinct().collect(Collectors.toMap(k -> k.getPCoinType() + "_" + k.getPMoneyType(),
                                k -> k.getPCoinType() + "_" + k.getPMoneyType(), (k, v) -> v));

//list to map(key&value多个字段)
Map resMap = positionDtos.stream()
.collect(Collectors.toMap(k -> k.getExchange() + "_" + k.getFbgSymbol(), pos->pos));

你可能感兴趣的:(Lambda的使用)