Map to add String value to each element in Java

Java 8Object Oriented ProgrammingProgramming

Let’s say the following is our String List −

List list = Arrays.asList("Football", "Basketball", "Hockey", "Cricket","Fencing");

Now, map to add string to each element −

List str = list.stream().map(name -> "Sports " + name + " Outdoor")
   .collect(Collectors.toList());

Above, we have added “Sports” and “Outdoor” strings to each element.

The following is an example to Map and add string value to each element in Java −

Example

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class Demo {
   public static void main(String[] args) {
      List list = Arrays.asList("Football", "Basketball", "Hockey", "Cricket","Fencing");
      List str = list.stream().map(name -> "Sports " + name + " Outdoor")
      .collect(Collectors.toList());
      System.out.println(str);
   }
}

Output

[Sports Football Outdoor, Sports Basketball Outdoor, Sports Hockey Outdoor, Sports Cricket Outdoor, Sports Fencing Outdoor]
raja
Published on 09-May-2019 09:02:47
Advertisements