映射到将字符串值添加到 Java 中每个元素


假设我们的 String List 如下所示 −

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

现在映射到每个元素以添加字符串 −

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

上面,我们已经向每个元素添加了“Sports”和“Outdoor”字符串。

以下是映射和在 Java 中向每个元素添加字符串值的一个示例 −

示例

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

输出

[Sports Football Outdoor, Sports Basketball Outdoor, Sports Hockey Outdoor, Sports Cricket Outdoor, Sports Fencing Outdoor]

更新时间: 30-Jul-2019

707 次浏览

开启你的 职业生涯

完成课程获取认证

开始
广告