Home > OS >  Replace Java for loop with Stream API
Replace Java for loop with Stream API

Time:10-13

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] = responseItems.get(i);
}

I want to replace for-loop with something like:

Arrays.stream(people.forEach(person -> names[i] = persons.get(i)));

CodePudding user response:

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

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

String[] names = people.values().toArray(String[]::new);

CodePudding user response:

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.

  • Related