3

HashMap inline initialization

 3 years ago
source link: https://marco.dev/hashmap-inline-initialization/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Create and initialize HashMap inline in a lambda stream

Working with Spring Integration I had the need to create MessageHeaders class in a Lambda expression.The MessageHeaders object requires an HashMap as constructor parameter and the inline initializations of an HashMap is not the most intuitive. The solution:

@Override
public List<Message> handleFileRequest() {
// we create a list from an enumerator
List<Message> messageList = Arrays.stream(FileType.values())
      // we read the file content from an external provider
      .map(externalProviderService::readFileFromExternalProvider)
      // for each object we create a new message
      .map(file -> MessageBuilder.createMessage(file,
         new MessageHeaders(new HashMap<String, Object>() { {
        put("fileName", file.getTitle());
      } })))
      .collect(Collectors.toList());

  return messageList;
}

In detail:

new HashMap<String, Object>() { {put("valueText", Object} }

The first brace ({ }) creates an Anonymous Inner Class, the second brace initializes a block inside the Anonymous Inner Class. This Java notation is not new but very unusual.

You can consider to call an external method to generate your hashmap.

Author

Marco Molteni

Marco Molteni Blog


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK