简体   繁体   中英

How to iterate list of hashmaps and map hashmap to model

I have face with the problem of iterating list of hashmaps where I want to map a particular hashmap with model.

result = {ArrayList@10441}  size = 3
 0 = {HashMap@10443}  size = 3
  0 = {HashMap$Node@10453} "Id" -> "3"
  1 = {HashMap$Node@10454} "Name" -> "name3"
  2 = {HashMap$Node@10455} "TimeSpent" -> "6543"
 1 = {HashMap@10444}  size = 3
 2 = {HashMap@10445}  size = 3

I tried to iterate it such a way:

list.forEach(e -> SourceTargetMapper.MAPPER.toModel(new Source((Map<String, Object>) e)))

'toModel()' returns such a model:

@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
public class Foo {

    private Long id;

    private String name;

    private Long timeSpent;
}

But I cannot collect mapped models to list again. How I can do it?

foreach() is not designed to map the stream elements : it is a terminal operation that "consumes" the stream with a Consumer .

Instead, use map() with collect() (supposing that Model is the returned type of toModel() :

List<Model> models = 
list.stream()
    .map(e -> SourceTargetMapper.MAPPER.toModel(new Source((Map<String, Object>) e)))
    .collect(Collectors.toList());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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