Salesforce Apex:如何不使用循环拆分自定义对象列表
在Apex中无循环拆分Product列表按type分组并提取productValue
你可以利用Apex的Stream API(API版本45.0及以上支持)来实现无显式循环的分组和提取操作,核心是借助Collectors.groupingBy进行分组,再通过map操作提取目标字段。
代码实现示例
假设你的自定义Product对象API名为Product__c,对应字段为Type__c(原type)和ProductValue__c(原productValue),代码如下:
// 原始Product列表 List<Product__c> productList = new List<Product__c>{ new Product__c(Type__c = 'fruit', ProductValue__c = 'apple'), new Product__c(Type__c = 'fruit', ProductValue__c = 'pineapple'), new Product__c(Type__c = 'vegetable', ProductValue__c = 'potato'), new Product__c(Type__c = 'vegetable', ProductValue__c = 'carrot') }; // 按Type__c分组,生成键为type值、值为对应Product列表的Map Map<String, List<Product__c>> groupedByType = productList.stream() .collect(Collectors.groupingBy(Product__c::getType__c)); // 提取fruit对应的productValue列表 List<String> fruitList = groupedByType.get('fruit').stream() .map(Product__c::getProductValue__c) .collect(Collectors.toList()); // 提取vegetable对应的productValue列表 List<String> vegetableList = groupedByType.get('vegetable').stream() .map(Product__c::getProductValue__c) .collect(Collectors.toList()); // 验证输出 System.debug('fruitList: ' + fruitList); // 输出: fruitList: (apple, pineapple) System.debug('vegetableList: ' + vegetableList); // 输出: vegetableList: (potato, carrot)
关键说明
Collectors.groupingBy(Product__c::getType__c):通过方法引用按Type__c字段分组,内部逻辑由Apex Stream处理,无需手动编写循环。map(Product__c::getProductValue__c):将每个Product对象转换为对应的ProductValue__c字符串值。- 如果你的Product是自定义Apex类(而非SObject),只需将字段的getter方法替换为类的属性调用即可,比如
Product::getType和Product::getProductValue。
内容的提问来源于stack exchange,提问作者Frii75
相关产品推荐
相关产品推荐

