Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/logging/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
将两个for循环转换为Java流?_Java_For Loop_Collections_Stream_Collectors - Fatal编程技术网

将两个for循环转换为Java流?

将两个for循环转换为Java流?,java,for-loop,collections,stream,collectors,Java,For Loop,Collections,Stream,Collectors,我有下面的嵌套for循环,我想将其转换为使用流,因为我目前正在学习使用流,如何才能这样做 我已经在下面添加了我当前的尝试,但它目前不完整 Part part = getPart(); List<Machines> machines = new ArrayList<>(); List<String> identities = getMachineIdentities(); Set<MachinePart> machineParts = new Has

我有下面的嵌套for循环,我想将其转换为使用流,因为我目前正在学习使用流,如何才能这样做

我已经在下面添加了我当前的尝试,但它目前不完整

Part part = getPart();
List<Machines> machines = new ArrayList<>();
List<String> identities = getMachineIdentities();
Set<MachinePart> machineParts = new HashSet<>();

    //create machines
    for (String identity : identities) {
               Machine machine = getMachine(identity);
               machines.add(machine);
           }

    //map to MachineParts
    for (Machine machines : machines) {
               MachinePart machinePart = MachinePartCreator.new(machines, part);
               machineParts.add(machinePart);
           }
Part-Part=getPart();
列表机器=新的ArrayList();
列表标识=getMachineIdentities();
Set machineParts=new HashSet();
//创造机器
for(字符串标识:标识){
Machine=getMachine(标识);
机器。添加(机器);
}
//映射到机器零件
用于(机器:机器){
MachinePart MachinePart=MachinePartCreator.new(机器,零件);
machineParts.add(machinePart);
}
流尝试:

Set<MachinePart > machineParts = identities.stream()
    .map(identity-> ??? ).collectors.collect(Collectors.toSet()));
Set machineParts=Identifies.stream()
.map(identity->??).collector.collect(collector.toSet());

第一个循环为第二个循环创建输入。这可以通过两个
map()
调用来实现:

Set<MachinePart> machineParts =
    identities.stream()
              .map(id -> getMachine(id))
              .map(m -> MachinePartCreator.new(m, part))
              .collect(Collectors.toSet());
设置机器部件=
identifies.stream()
.map(id->getMachine(id))
.map(m->MachinePartnerCreator.new(m,零件))
.collect(收集器.toSet());
甚至有一个:

Set<MachinePart> machineParts =
    identities.stream()
              .map(id -> MachinePartCreator.new(getMachine(id),part))
              .collect(Collectors.toSet());
设置机器部件=
identifies.stream()
.map(id->machineParCreator.new(获取机器(id),零件))
.collect(收集器.toSet());

当然,您也可以使用单个for循环编写原始代码,并跳过中间的
列表机器

谢谢,两个.map()行中发生了什么?只是想了解一下我自己的知识。@java12399900第一个
map
调用将
转换为
,第二个
map
调用将
转换为
流。谢谢,在这里使用流有什么好处,我觉得循环更容易调试和阅读?@java12399900我认为这样的基本代码不需要太多调试。一旦你习惯了流,它们可能会变得更容易阅读。但总的来说有什么好处?