jdk1.8新特性
程序员文章站
2022-03-04 08:41:50
...
jdk.1.8 新特性之集合
遍历集合中的对象:
/**
* java8 新特性
* 遍历集合中的对象
*/
@Test
public void method01() {
ArrayList<Person> list = new ArrayList<>();
Person p1 = new Person("p1的名字",20);
Person p2 = new Person("p2的名字",22);
Person p3 = new Person("p3的名字", 30);
list.add(p1);
list.add(p2);
list.add(p3);
list.stream().forEach(person ->{
System.out.println(person.getName());
});
}
/**
* 将 List 集合转化成 map 集合
*/
@Test
public void method2 () {
ArrayList<Person> list = new ArrayList<>();
Person p1 = new Person("p1的名字",20 , 1);
Person p2 = new Person("p2的名字",22,2);
Person p3 = new Person("p3的名字", 30,3);
list.add(p1);
list.add(p2);
list.add(p3);
//将id 作为 key 转成map
Map<Integer, Person> map = list.stream().collect(Collectors.toMap(Person :: getId , a -> a ,(k1,k2)->k1));
System.out.println(map);
}
/**
* List 里面的对象元素, 以某个属性来分组
*/
@Test
public void method3 () {
ArrayList<Person> list = new ArrayList<>();
Person p1 = new Person("张三",20 , 1);
Person p2 = new Person("李栋",22,2);
Person p3 = new Person("李栋", 23,3);
Person p4 = new Person("李四", 34,3);
list.add(p1);
list.add(p2);
list.add(p3);
list.add(p4);
//根据名称 name 将 list 分组
Map<String, List<Person>> map = list.stream().collect(Collectors.groupingBy(Person::getName));
System.out.println(map.toString());
}
/**
* 从集合中过滤出符合条件的数据
*/
@Test
public void method4() {
ArrayList<Person> list = new ArrayList<>();
Person p1 = new Person("张三",20 , 1);
Person p2 = new Person("李栋",22,2);
Person p3 = new Person("李栋", 23,3);
Person p4 = new Person("李四", 34,3);
list.add(p1);
list.add(p2);
list.add(p3);
list.add(p4);
//取出名字为张三的用户信息
List<Person> filterCtList = list.stream().filter(Person -> Person.getName().equals("张三")).collect(Collectors.toList());
filterCtList.forEach(Person -> {
System.out.println(Person.getName());
});
}
/**
* 将集合中的数据按照某个属性进行求和
*/
@Test
public void method5() {
ArrayList<Person> list = new ArrayList<>();
Person p1 = new Person("张三",20 , 1);
Person p2 = new Person("李栋",22,2);
Person p3 = new Person("李栋", 23,3);
Person p4 = new Person("李四", 34,3);
list.add(p1);
list.add(p2);
list.add(p3);
list.add(p4);
int sum = list.stream().mapToInt(Person::getAge).sum();
System.out.println(sum);
}
/**
* 将list 转 map
*/
@Test
public void method6() {
ArrayList<Person> list = new ArrayList<>();
Person p1 = new Person("张三",20 , 1);
Person p2 = new Person("李栋",22,2);
Person p3 = new Person("李栋", 23,3);
Person p4 = new Person("李四", 34,4);
list.add(p1);
list.add(p2);
list.add(p3);
list.add(p4);
Map<Integer, Person> map = list.stream().collect(Collectors.toMap(Person::getId, person -> person));
System.out.println(map.toString());
}
转载于:https://www.jianshu.com/p/6fa198649b6a