1

My code:

Map<Integer, String> people = Map.of(
      1, "John", 2, "Michael", 3, "Bob", 4, "Liza", 5, "Anna"
 );

String[] names = new String[people.size];

for (int i = 1; i < names.length; i++) {
     names[i] = people.get(i);
}

I want to replace for-loop with something like:

Arrays.stream(people.forEach(person -> names[i] = persons.get(i)));
7
  • 5
    Does it have to be a stream? Can't you use persons.values().toArray(new String[0])? Commented Oct 13, 2022 at 14:14
  • @Ivar Yeah, sure, it have to be a stream. But thanks for suggested solution. Commented Oct 13, 2022 at 14:22
  • @DmitriyDmitruk It is suspicious that you do not accept Ivar's solution. What you really want to achieve? Ivar's solution is the most correct replacement of your code. Please read xyproblem.info Commented Oct 13, 2022 at 14:37
  • @Alexander Are you sure it is people and not responseItems as originally posted? Not the best idea to make such changes to posted code IMO! Or did I miss some comment? Commented Oct 13, 2022 at 14:41
  • @user16320675 I've made a conclusion that these collections are the same, judging by the OP's response to the comment Ivar, where OP says that the code which Ivar has provided does what expected, but they want to use a Stream. Commented Oct 13, 2022 at 14:51

4 Answers 4

3

You can use IntStream.range() (or rangeClosed()) and Stream.toArray() to implement the same logic with Stream API:

Map<Integer, String> people = Map.of(
    1, "John", 2, "Michael", 3, "Bob", 4, "Liza", 5, "Anna"
);
        
String[] names = IntStream.rangeClosed(1, 5)
    .mapToObj(people::get)
    .toArray(String[]::new);

If the keys of the original map are not integers, or the map is represented by a plain HashMap which is incapable of maintaining the order, but you need to reflect the ordering of keys in the resulting array, then create a stream of entries and sort them by key as suggested by @Holger:

String[] names = people.entrySet().stream()
    .sorted(Map.Entry.comparingByKey())
    .map(Map.Entry::getValue)
    .toArray(String[]::new);

In case if the order of elements is not important, then you can use Collection.toArray():

String[] names = people.values().toArray(String[]::new);
Sign up to request clarification or add additional context in comments.

4 Comments

The for loop looks better, IMO.
@RobertHarvey but the loop code has an off-by-one error. So don’t tell me that the loop was more readable when no-one spotted the error yet…
But maybe, String[] names = people.entrySet().stream() .sorted(Map.Entry.comparingByKey()).map(Map.Entry::getValue).toArray(String[]::new); would be the even more reliable solution…
@Holger Good point, incorporated this solution into the answer.
0

I hope this can help you.

 Map<Integer, String> persons = new HashMap<>();
//Option one
    String[] names = persons.entrySet().stream().map(e-> e.getValue())
                            .collect(Collectors.toList()).toArray(new String[0]);
    //Option two
            persons.values().stream().collect(Collectors.toList()).toArray(new String[0]);

Just transform the map to list and then make it an Array, well, we use a stream in the collection values or in the entrySet.

1 Comment

There’s no sense in collecting into a List, just to call toArray on it, as you can call toArray on the stream in the first place. Just use toArray(String[]::new) instead of toArray(new String[0])
0
Map<Integer, String> people = Map.of(
    1, "John", 2, "Michael", 3, "Bob", 4, "Liza", 5, "Anna"
);

String[] unorderedNames = people.values().toArray(String[]::new);
String[] namesInTheSameOrder = people.entrySet().stream().map(Map.Entry::getValue).toArray(String[]::new);

1 Comment

Instead of entrySet().stream().map(Map.Entry::getValue) you can use values().stream() in the first place.
0

You can use the below approaches to get the desired results:

Here,

  • Approach 1 : Took the values from the map and converted into Array. No sorting is considered here.
  • Approach 2: Took the entrySet() and sorted by the key of the map and converted the entryset into values using map() and then converted into Array. Sorting is considered here.

Code:

public class Test {
    public static void main(String[] args) {
        Map<Integer, String> people = 
                Map.of(1, "John", 2, "Michael", 3, "Bob", 4, "Liza", 5, "Anna");

        //Approach 1 : Data without sorting
        String[] peopleNames = people.values().toArray(String[]::new);

        //Approach 2: Data with sorting by key of the map
        String[] peopleNamesSortedByKey = people.entrySet().stream()
                .sorted(Map.Entry.comparingByKey())
                .map(Map.Entry::getValue).toArray(String[]::new);
    }
}

Output::

Bob Michael John Anna Liza // No sorting
John Michael Bob Liza Anna // Sorted by Key

Comments

Your Answer

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.