Lambda expression traversal combined with some commonly used operations

        Lambda expression is a new feature of JDK 8. Lambda can replace most anonymous inner classes and write better Java code, especially in collection traversal and other collection operations, which can greatly optimize the code structure. Lambda consists of parameter list, arrow symbol -> and function body.

        stream() is not a data structure, it is just a view of some kind of data source, the data source can be an array, Java container or I/O channel, etc. Born for functional programming. Any modification to the stream will not modify the data source behind it. For example, performing a filter operation on the stream will not delete the filtered elements, but will generate a new stream that does not contain the filtered elements. The operation on the stream will not be executed immediately, but will only be executed when the user really needs the result. The stream can only be "consumed" once, and once it is traversed, it will become invalid, just like the iterator of the container, it must be regenerated if it wants to traverse it again.

Collection grouping (get Map<String, List<R>>)

group writing

public static void main(String[] args) {
        // 构建实体对象 模拟从数据查到的数据 
        PersonEntity person1 = PersonEntity.builder().userId("1").userName("张三").userStatus("1").roomNumber("101").build();
        PersonEntity person_1 = PersonEntity.builder().userId("1").userName("张三").userStatus("-1").roomNumber("101").build();
        PersonEntity person2 = PersonEntity.builder().userId("2").userName("李四").userStatus("1").roomNumber("101").build();
        PersonEntity person3 = PersonEntity.builder().userId("3").userName("王五").userStatus("1").roomNumber("102").build();
        // personAllList添加实体 全部人员
        List<PersonEntity> personAllList = new ArrayList<>();
        personAllList.add(person1);
        personAllList.add(person2);
        personAllList.add(person3);
        Map<String, List<PersonEntity>> map = personAllList.stream().collect(Collectors.groupingBy(PersonEntity::getRoomNumber));
        System.out.println(map.toString());
    }

print result

{101=[PersonEntity(userId=1, userName=张三, userStatus=1, roomNumber=101), PersonEntity(userId=2, userName=李四, userStatus=1, roomNumber=101)], 102=[PersonEntity(userId=3, userName=王五, userStatus=1, roomNumber=102)]}

Get an element with the maximum value of the entity attribute in the collection

 // 获取id最大的用户
Optional<PersonEntity> personEntity= personAllList.stream().max(Comparator.comparing(PersonEntity::getUserId));

Get the entity attribute in the collection and save it as a new MAP(Map<String, String>)

Map<String, String> map = list.stream().collect(Collectors.toMap(vo::getxxx, vo::getxxx));

Duplicate key xxxx exception

When we use Lambda to convert a list into a Map, the exception of Duplicate key xxxx will appear, which means that the key to be converted into a map is duplicated. In addition to the for loop deduplication, we have other ways to handle it gracefully it.

1.key重复时直接用后面的值(使用最新的或最老的值)
Map<String, Long> collect = enterpriseWechatRelations.stream().collect(Collectors.toMap(EnterpriseWechatRelation::getExternalUserId, EnterpriseWechatRelation::getUserId,(val1, val2) -> val2));
2.将两个值拼接起来
Map<String, Long> collect = enterpriseWechatRelations.stream().collect(Collectors.toMap(EnterpriseWechatRelation::getExternalUserId,EnterpriseWechatRelation::getUserId,(val1, val2) -> val1+val2));

Get a new entity in the entity attribute in the combination (List<BeanB>)

List<BeanB> newList = oldList.stream().map(e -> new BeanB(e.getId(), e.getName(), e.getAge())).collect(Collectors.toList());

The expression sorts the age in positive order (sorted and reversed())

// 正序
userInfoList = userInfoList.stream().sorted(Comparator.comparing(UserInfo::getAge)).collect(Collectors.toList());
// 逆序
userInfoList=userInfoList.stream().sorted(Comparator.comparing(UserInfo::getAge).reversed()) .collect(Collectors.toList());

filter into a new collection based on some attribute

List<Category> categoryList = categoryService.selectCategoryList(category);
// 选出所有一级分类放入新的集合
List<Category> listLevel1=categoryList.stream().filter((Category c) ->"1".equals(c.getCategoryLevel())).collect(Collectors.toList());

//    获取设备类型为102的摄像头集合
List<AiDevice> cameraList=list.stream().filter((AiDevice b)- 
>"102".equals(b.getDeviceType())).distinct().collect(Collectors.toList());
// 然后根据摄像头对应的gatemateId 找到需要下发的盒子信息
List<AiDevice> result = cameraList.stream().collect(Collectors.collectingAndThen(
Collectors.toCollection(() -> new TreeSet<> 
(Comparator.comparing(AiDevice::getGatewayId))), ArrayList::new));

deduplication by name

List<ProdAPP> list =listOld.stream().collect(
        Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(o -> o.getProdName()))),ArrayList::new));

Simple sets take intersection, difference, union, deduplication union

List<String> list1 = new ArrayList();
List<String> list2 = new ArrayList();
// 交集
List<String> intersection = list1.stream().filter(item -> list2.contains(item)).collect(Collectors.toList());
// 差集 (list2 - list1)
List<String> reduce2 = list2.stream().filter(item -> !list1.contains(item)).collect(Collectors.toList());
// 并集
List<String> listAll = list1.parallelStream().collect(Collectors.toList());
List<String> listAll2 = list2.parallelStream().collect(Collectors.toList());
listAll.addAll(listAll2);
// 去重并集
List<String> listAllDistinct = listAll.stream().distinct().collect(Collectors.toList());

Some summation and accumulation use lambda

 // 汇总1:单列累加 
goodsInfoList.stream().map(GoodsInfoDTO::getPrice).reduce(BigDecimal.ZERO, BigDecimal::add);
// 汇总2:先过滤再单列累加(55.0)
goodsInfoList.stream().filter(goods ->         
"MATERIAL".equals(goods.getGoodsType())).map(GoodsInfoDTO::getPrice).reduce(BigDecimal.ZERO, BigDecimal::add);
// 汇总3:双列乘积并累加
goodsInfoList.stream().map(x -> x.getPrice().multiply(BigDecimal.valueOf(x.getQty()))).reduce(BigDecimal.ZERO, BigDecimal::add);
// 积汇4:双列乘积并累加
goodsInfoList.stream().reduce(BigDecimal.ZERO, (x, y) -> {
            return x.add(y.getPrice().multiply(BigDecimal.valueOf(y.getQty())));
        }, BigDecimal::add);
// 整形
 list.stream().mapToInt(a->a.getCount()).sum()
// double类型
list.stream().mapToDouble(a->a.getWeight()).sum();
// Long类型
list.stream().mapToLong(a -> a.getPri()).sum();
// BigDecimal类型
list.stream().map(Animal::getMoney).reduce(BigDecimal.ZERO, BigDecimal::add);

Guess you like

Origin blog.csdn.net/neusoft2016/article/details/131186308