import lombok.Data;
import org.junit.Test;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
* @author lilili
* @version 0.0.1
*/
public class TestStream {
List<Student> studentList = Arrays.asList(
new Student("小1", 18, 5000.00),
new Student("小2", 28, 10000.00),
new Student("小3", 10, 100000.00),
new Student("小4", 48, 1000000.00),
new Student("小5", 58, 10000000.00)
);
@Test
public void testStream1() {
studentList.stream().filter(s -> s.getAge() > 10).forEach(System.out::println);
studentList.stream().filter(s -> s.getAge() > 10).limit(1).forEach(System.out::println);
studentList.forEach(System.out::println);
System.out.println("----------------获取studentList所有的name生产一个新的的集合-----------------");
List<String> names =
studentList.stream()
.map(Student::getName)
.collect(Collectors.toList());
names.forEach(System.out::println);
System.out.println("-------------------获取studentList所有的age并且排序生产一个新的集合-----------------------");
List<Integer> ages =
studentList.stream()
.map(Student::getAge)
.sorted()
.collect(Collectors.toList());
ages.forEach(System.out::println);
System.out.println("----------------获取studentList 所有age>18的同学名称生产一个新的集合--------------------------");
List<String> names2 =
studentList.stream()
.filter(student -> student.getAge() > 18)
.map(Student::getName)
.collect(Collectors.toList());
names2.forEach(System.out::println);
System.out.println("----------------转换studentList to map 并且以name当做key--------------------------");
Map<String, Student> settingVoMap =
studentList
.stream()
.collect(Collectors.toMap(Student::getName, a -> a, (k1, k2) -> k1));
System.out.println(settingVoMap);
System.out.println(settingVoMap.get("小2"));
}
}
@Data
class Student {
public String name;
public int age;
public Double salary;
public Student(String name, int age, Double salary) {
this.name = name;
this.age = age;
this.salary = salary;
}
}
Java8 Lambda表达式-Stream API
猜你喜欢
转载自blog.csdn.net/lucklilili/article/details/108548640
今日推荐
周排行