Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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.

share|improve this question

1 Answer 1

up vote 4 down vote accepted

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];
    }
});
share|improve this answer
    
Awesome! Thank you very much nosid for my saved time! –  Arthur Khusntudinov May 30 at 9:31
    
But what imagesStream.toArray(HashMap[]::new) means? Is it lambda? Can you send me full form of the imagesStream.toArray(HashMap[]::new), without lambda? –  Arthur Khusntudinov May 30 at 9:33
    
Great! Thank you very much! –  Arthur Khusntudinov May 30 at 9:47

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.