toMap toList toCollection joining
视频讲解:https://www.bilibili.com/video/av77800638/
EmployeeTestCase.java
package com.example.demo; import lombok.extern.log4j.Log4j2; import org.junit.Test; import java.io.IOException; import java.io.PrintWriter; import java.nio.file.Files; import java.nio.file.Paths; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Vector; import java.util.stream.Collectors; import java.util.stream.Stream; @Log4j2 public class EmployeeTestCase extends BaseTestCase { @Test public void collector() { //转换成连接字符串 String strName = list.stream().map(Employee::getName).collect(Collectors.joining(",")); log.info("strName:{}", strName); //转换成Set集合 Set<String> setName = list.stream().map(Employee::getName).collect(Collectors.toSet()); log.info("setName:{}", strName); //转换成Vector Vector<String> vectorName = list.stream().map(Employee::getName).collect(Collectors.toCollection(Vector::new)); //转换成List List<String> listName = list.stream().map(Employee::getName).collect(Collectors.toList()); //转换成Map Map<Long, String> mapName = list.stream().collect(Collectors.toMap(employee -> employee.getId(), employee -> employee.getName())); } }
BaseTestCase.java
package com.example.demo; import java.util.Arrays; import java.util.List; public class BaseTestCase { protected static final List<Employee> list = Arrays.asList( new Employee(1, "Alex", 1000), new Employee(2, "Michael", 2000), new Employee(3, "Jack", 1500), new Employee(4, "Owen", 1500), new Employee(5, "Denny", 2000)); }
关注公众号,坚持每天3分钟学习