简体   繁体   English

列表和stream.map()中的Java 8迭代列表

[英]Java 8 Iterate List inside an list and stream.map()

I am wondering if there is a single line option for this issue. 我想知道是否存在针对此问题的单行选项。

I have a bean like, 我有一个豆子

public class DataA {
    private String name;
    private String email;
    private List<String> accountNumberName;
}

Sample value in DataA is DataA中的样本值为

name="user1",email="user@abcom",accountNumberName=["100", "101", "102"] etc.. name="user1",email="user@abcom",accountNumberName=["100", "101", "102"]等。

I have a map of account number and Name Map<String, String> accountNumberNameMap Sample data in accountNumberNameMap is like, 我有地图的账号和姓名Map<String, String> accountNumberNameMap在样本数据accountNumberNameMap就好了,

{"100"="Account A", "101" = "Account B", "102" = "Account C"}

I want to convert DataA to name="user1",email="user@abcom",accountNumberName=["100 - Account A", "101 - Account B", "102 - Account C"] 我想将DataA转换为name="user1",email="user@abcom",accountNumberName=["100 - Account A", "101 - Account B", "102 - Account C"]

I have a collection of DataA List<DataA> want to convert all my accountNumberName inside the 'List' to have account number - Account name using accountNumberNameMap . 我有一个DataA List<DataA>的集合,想要将“列表”内的所有accountNumberName转换为具有account number - Account name使用accountNumberNameMap account number - Account name

I can do it by using couple of loops and then convert account Number to account number - account Name. 我可以通过使用几个循环来完成,然后将帐号转换为帐号-帐号名。 Wondering if there is a easy way in Java8 stream to do it. 想知道Java8流中是否有简单的方法可以做到这一点。

If you don't mind modifying the instances in the list directly, you can use forEach combined with replaceAll (I assumed I could access the accountNumberName for simplicity but you can easily change it also via a setter). 如果您不介意直接修改列表中的实例,则可以将forEachreplaceAll结合使用(为简化起见,我可以访问accountNumberName ,但也可以通过setter轻松更改它)。

list.forEach(d -> d.accountNumberName.replaceAll(acc -> acc + " - " + accountNumberNameMap.getOrDefault(acc, "")));

If you don't want to modify the existing instances, it can be done this way (assuming a copy constructor exists): 如果您不想修改现有实例,则可以通过以下方式完成(假设存在复制构造函数):

list.replaceAll(d -> new DataA(d.name, d.email, d.accountNumberName.stream().map(name -> name + " - " + accountNumberNameMap.getOrDefault(name, "")).collect(toList())));

(and then if you don't want to modify the original list, just stream/collect over it instead of using replaceAll ) (然后,如果您不想修改原始列表,只需对其进行流式处理/收集,而不是使用replaceAll

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM