定义一个集合,并添加一些整数1,2,3,4,5,6,7,8,9,10,过滤奇数,只留下偶数,并将结果保存起来。
package MyStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Test1 {
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);
}
}
创建一个ArrayList集合并添加以下字符,字符串中前面是姓名,后面是年龄,“zhangsan,23”,"lisi,24","wagwu,25",保留年龄大于等于24岁的人,并将结果收集到Map集合当中,姓名为键,年龄为值。
package MyStream;
import java.util.ArrayList;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
public class Test2 {
public static void main(String[] args) {
ArrayList<String> list=new ArrayList<>();
list.add("zhangsan,23");
list.add("lisi,24");
list.add("wangwu,25");
/* list.stream().filter(s->Integer.parseInt(s.split(",")[1])>=24)
.collect(Collectors.toMap(new Function<String, String>() {
@Override
public String apply(String s) {
return s.split(",")[0];
}
}, new Function<String, Integer>() {
@Override
public Integer apply(String s) {
return Integer.parseInt(s.split(",")[1]);
}
}));*/
Map<String,Integer> map=list.stream().filter(s->Integer.parseInt(s.split(",")[1])>=24)
.collect(Collectors.toMap(
s->s.split(",")[0] ,
s->Integer.parseInt(s.split(",")[1])));
System.out.println(map);
}
}
package MyStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Test3 {
public static void main(String[] args) {
ArrayList<String> manList=new ArrayList<>() ;
ArrayList<String> womenList=new ArrayList<>() ;
Collections.addAll(manList,"蔡坤坤,24","叶齁咸,23","刘不甜,22","吴签,24","谷嘉,30","肖梁梁,27");
Collections.addAll(womenList,"赵小颖,35","杨颖,36","高元元,43","张天天,31","刘诗,35","杨小幂,33");
Stream<String> stream1 = manList.stream().filter(s -> s.split(",")[0].length() == 3)
.limit(2);
Stream<String> stream2 = womenList.stream().filter(s -> s.split(",")[0].startsWith("杨"))
.skip(1);
/*Stream.concat(stream1,stream2).map(new Function<String,Actor>() {
@Override
public Actor apply(String s) {
String name=s.split(",")[0];
int age=Integer.parseInt(s.split(",")[1]);
return new Actor(name,age);
}
}).forEach(s-> System.out.println(s));*/
List<Actor> list= Stream.concat(stream1,stream2).map(s->
new Actor(s.split(",")[0],Integer.parseInt(s.split(",")[1]))
).collect(Collectors.toList());
System.out.println(list);
}
}