Dmitriy Dmitruk
Dmitriy Dmitruk

Reputation: 11

Replace Java for loop with Stream API

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)));

Upvotes: 1

Views: 168

Answers (4)

iamgirdhar
iamgirdhar

Reputation: 1155

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

Upvotes: 0

Alexander Ivanchenko
Alexander Ivanchenko

Reputation: 28988

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);

Upvotes: 3

Not A Number
Not A Number

Reputation: 196

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);

Upvotes: 0

AbrahamSantos
AbrahamSantos

Reputation: 169

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.

Upvotes: 0

Related Questions