package start.java8;
import org.junit.Test;
import start.entity.Student;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
public class TestJava8 {
private static List<Student> studentList = new ArrayList<>();
static {
Student stu = new Student("1", "张三", 21, "北京", "0573");
studentList.add(stu);
Student stu2 = new Student("2", "李四", 22, "上海", "0572");
studentList.add(stu2);
Student stu3 = new Student("3", "王五", 23, "杭州", "0571");
studentList.add(stu3);
Student stu4 = new Student("3", "王五", 23, "杭州", "0571");
studentList.add(stu4);
}
/**
* list转map
*/
@Test
public void test01() {
Map<String, Student> listMap = studentList.stream().collect(Collectors.toMap(Student::getId, Function.identity(), (key1, key2) -> key2));
Map<String, String> listMap2 = studentList.stream().collect(Collectors.toMap(Student::getId, Student::getName));
System.out.println(listMap);
System.out.println(listMap2);
}
/**
* map转list
*/
@Test
public void test02() {
Map<Integer, List<String>> map = new HashMap<>();
map.put(1, Arrays.asList("apple", "banana"));
map.put(2, Arrays.asList("cat", "dog", "pig"));
map.put(3, Arrays.asList("fish"));
List<String> list = map.values().stream().flatMap(Collection::stream).collect(Collectors.toList());
System.out.println(list);
}
/**
* list过滤
*/
@Test
public void test03() {
List<Student> filterList = studentList.stream().filter(student -> student.getAge() < 24 && student.getPhone().startsWith("0571")).collect(Collectors.toList());
System.out.println(filterList);
}
/**
* list排序、去重
*/
@Test
public void test04() {
// 单个字段排序
List<Student> sortedList = studentList.stream().sorted(Comparator.comparing(Student::getAge)).collect(Collectors.toList());
System.out.println(sortedList);
// 多个字段排序
List<Student> sortedList2 = studentList.stream()
.sorted(Comparator.comparing(Student::getName).thenComparing(Student::getAge))
.collect(Collectors.toList());
System.out.println(sortedList2);
// 单个字段倒序
List<Student> sortedList3 = studentList.stream()
.sorted(Comparator.comparing(Student::getAge).reversed())
.collect(Collectors.toList());
System.out.println(sortedList3);
// 单个字段排序并去重
List<Student> sortedList4 = studentList.stream()
.sorted(Comparator.comparing(Student::getAge))
.distinct()
.collect(Collectors.toList());
System.out.println(sortedList4);
}
/**
* 获取工作表某个属性的list集合
*/
@Test
public void test05() {
List<String> nameList = studentList.stream().map(Student::getName).collect(Collectors.toList());
System.out.println(nameList);
}
}
Java8常用函数
于 2023-09-21 16:26:32 首次发布