取偶数
package stream;import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;public class StreamDemo2 {public static void main(String[] args) {ArrayList<Integer> list = new ArrayList<>();Collections.addAll(list, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10);List<Integer> newlist = list.stream().filter(n -> n % 2 == 0).collect(Collectors.toList());System.out.println(newlist);}
}
查找年龄大于24岁的,并把名字当做键,年龄当作值存入map表里面
package stream;import java.util.ArrayList;
import java.util.Collections;
import java.util.Map;
import java.util.stream.Collectors;public class StreamDemo3 {public static void main(String[] args) {ArrayList<String> list = new ArrayList<>();Collections.addAll(list,"zhangsan,23","lisi,24","wamhwu,25");Map<String, String> map = list.stream().filter(s -> Integer.parseInt(s.split(",")[1]) >= 24).collect(Collectors.toMap(s -> s.split(",")[0], s -> s.split(",")[1]));System.out.println(map);}
}
男生查找姓名长度为三,并且选择前两个人,女生查找姓名姓杨,并且跳过第一个人,将两个查找到的人,一起放入到一个链表当中,创建Actor,给姓名和年龄赋值
package stream;import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;public class StreamDemo4 {public static void main(String[] args) {ArrayList<String> manlist = new ArrayList<>();ArrayList<String> womanlist = new ArrayList<>();Collections.addAll(manlist,"赵一鸣,22","田镇,23","吴邪,24","狄仁杰,25");Collections.addAll(womanlist,"貂蝉,22","王昭君,23","杨玉环,24","西施,25","杨桥,21","杨凯华,20");Stream<String> man = manlist.stream().filter(s -> s.split(",")[0].length() == 3).limit(2);Stream<String> woman = womanlist.stream().filter(s -> s.split(",")[0].startsWith("杨")).skip(1);List<Object> collect = Stream.concat(man, woman).map(s -> new Actor(s.split(",")[0], Integer.parseInt(s.split(",")[1]))).collect(Collectors.toList());System.out.println(collect);}
}
package stream;import java.util.Objects;public class Actor {public String name;public int age;public Actor() {}public Actor(String name, int age) {this.name = name;this.age = age;}@Overridepublic boolean equals(Object o) {if (this == o) return true;if (o == null || getClass() != o.getClass()) return false;Actor actor = (Actor) o;return age == actor.age && Objects.equals(name, actor.name);}@Overridepublic int hashCode() {return Objects.hash(name, age);}/*** 获取* @return name*/public String getName() {return name;}/*** 设置* @param name*/public void setName(String name) {this.name = name;}/*** 获取* @return age*/public int getAge() {return age;}/*** 设置* @param age*/public void setAge(int age) {this.age = age;}public String toString() {return "Actor{name = " + name + ", age = " + age + "}";}
}