2

I am newbie in Java 8 Streams. Please advice, how to Convert Stream Stream<HashMap<String, Object>> to HashMap Array HashMap<String, Object>[] ?

For example, I has some stream in code:

Stream<String> previewImagesURLsList = fileNames.stream();
Stream<HashMap<String, Object>> imagesStream = previewImagesURLsList
 .map(new Function<String, HashMap<String, Object>>() {
 @Override
 public HashMap<String, Object> apply(String person) {
 HashMap<String, Object> m = new HashMap<>();
 m.put("dfsd", person);
 return m;
 }
 });

How I can do something like

HashMap<String, Object>[] arr = imagesStream.toArray();

?

Sorry my bad English.

nosid
50.3k13 gold badges117 silver badges146 bronze badges
asked May 30, 2014 at 9:24
0

1 Answer 1

5

The following should work. Unfortunately, you have to suppress the unchecked warning.

@SuppressWarnings("unchecked")
HashMap<String, Object>[] arr = imagesStream.toArray(HashMap[]::new);

The expression HashMap[]::new is an array constructor reference, which is a kind of method reference. Method references provide an alternative way to implement functional interfaces. You can also use a lambda expression:

@SuppressWarnings({"unchecked", "rawtypes"})
HashMap<String, Object>[] array = stream.toArray(n -> new HashMap[n]);

Before Java 8, you would have used an anonymous inner class for that purpose.

@SuppressWarnings({"unchecked", "rawtypes"})
HashMap<String, Object>[] array = stream.toArray(new IntFunction<HashMap[]>() {
 public HashMap[] apply(int n) {
 return new HashMap[n];
 }
});
Brian Goetz
96.2k26 gold badges164 silver badges172 bronze badges
answered May 30, 2014 at 9:27

2 Comments

Awesome! Thank you very much nosid for my saved time!
But what imagesStream.toArray(HashMap[]::new) means? Is it lambda? Can you send me full form of the imagesStream.toArray(HashMap[]::new), without lambda?

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.