我有一个HashMap
,其中包含List<Dto>
和List<List<String>>
:
Map<List<Dto>, List<List<String>>> mapData = new HashMap();
和一个Arraylist<Dto>
。
我想遍历此映射,获取keys-key1,key2等,并从中获取值,并将其设置为Dto对象,然后将其添加到列表中。因此,我能够成功使用foreach进行迭代并将其添加到列表中,但无法使用Java 8正确完成它。因此,我需要一些帮助。这是示例代码
List<DTO> dtoList = new ArrayList();
DTO dto = new DTO();
mapData.entrySet().stream().filter(e->{
if(e.getKey().equals("key1")){
dto.setKey1(e.getValue())
}
if(e.getKey().equals("key2")){
dto.setKey2(e.getValue())
}
});
这里e.getValue()
来自List<List<String>>()
所以第一件事是我需要遍历它来设置值。
其次是我需要将dto添加到Arraylist dtoList中。那么如何实现这一目标。
我尝试不添加到HashMap中的基本代码片段,其中List具有键,multiList具有值,Dto list是我最终添加到的
for(List<Dto> dtoList: column) {
if ("Key1".equalsIgnoreCase(column.getName())) {
index = dtoList.indexOf(column);
}
}
for(List<String> listoflists: multiList) {
if(listoflists.contains(index)) {
for(String s: listoflists) {
dto.setKey1(s);
}
dtoList.add(dto);
}
}
答案 0 :(得分:0)
请参见https://docs.oracle.com/javase/8/docs/api/java/util/stream/package-summary.html
流操作分为中间操作和终端操作,并结合在一起形成流管道。流管道由一个源(例如Collection,数组,生成器函数或I / O通道)组成;随后是零个或多个中间操作,例如Stream.filter或Stream.map;以及诸如Stream.forEach或Stream.reduce之类的终端操作。
因此,在上面的代码段中,filter
并没有做任何事情。要触发它,请在最后添加一个collect
操作。请注意,filter lambda函数需要返回一个布尔值,以便代码首先进行编译。
mapData.entrySet().stream().filter(entry -> {
// do something here
return true;
}).collect(Collectors.toList());
当然,对于简单的任务,您不需要滥用中间操作-或生成一堆新对象,这样的操作就足够了:
mapData.entrySet().stream().forEach(entry -> {
// do something
});