Java8 Streams map 使用

1. 将 List 中的对象转为字符串

public class Developer {


  private String name;

  private BigDecimal salary;

  private Integer age;

  //...

}
public static void main(String[] args) {
    List persons = Arrays.asList(
        new Developer("zhangsan", 20),
        new Developer("lisi",21),
        new Developer("wangwu",22));

    //Before Java 8
    List result = new ArrayList<>();
    for (Developer developer : persons) {
      result.add(developer.getName());
    }

    System.out.println(result); // [zhangsan, lisi, wangwu]

    //Java 8
    List collect = persons.stream().map(x -> x.getName()).collect(Collectors.toList());
    System.out.println(collect); // [zhangsan, lisi, wangwu]
  }

2. 将 List 中的字符串转为大写

public static void main(String[] args) {
    List alpha = Arrays.asList("a", "b", "c", "d");

    //Before Java8
    List alphaUpper = new ArrayList<>();
    for (String s : alpha) {
      alphaUpper.add(s.toUpperCase());
    }

    System.out.println(alpha); //[a, b, c, d]
    System.out.println(alphaUpper); //[A, B, C, D]

    // Java 8
    List collect = alpha.stream().map(String::toUpperCase).collect(Collectors.toList());
    System.out.println(collect); //[A, B, C, D]

    // Extra, streams apply to any data type.
    List num = Arrays.asList(1,2,3,4,5);
    List collect1 = num.stream().map(n -> n * 2).collect(Collectors.toList());
    System.out.println(collect1); //[2, 4, 6, 8, 10]
  }

3. 将 List 中的对象转为另一个对象

List developers = Arrays.asList(
        new Developer("zhangsan", 20),
        new Developer("lisi",21),
        new Developer("wangwu",22));

List result = developers.stream().map(temp -> {
      Person person = new Person();
      person.setName(temp.getName());
      person.setAge(temp.getAge());

      if ("lisi".equals(temp.getName())) {
        person.setExtra("i am lisi");
      }
      return person;
    }).collect(Collectors.toList());

    System.out.println(JSONUtil.toJsonStr(result));      

你可能感兴趣的:(windows,java)