ArrayList<Integer>list=new ArrayList<>();
Collections.addAll(list,1,2,3,4,5,6,7,8,9,10);
List<Integer> list1 = list.stream()
.filter(s -> s % 2 == 0)
.collect(Collectors.toList());
System.out.println(list1);
[2, 4, 6, 8, 10]
ArrayList<String> list = new ArrayList<>();
Collections.addAll(list, "zhangsan,23", "lisi,24", "wangwu,25");
Map<String, Integer> map = 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]);
}
}
));
System.out.println(map);
//也可以用Lambda简写
/* Map 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);*/
{lisi=24, wangwu=25}
ArrayList<String> list1 = new ArrayList<>();
ArrayList<String> list2 = new ArrayList<>();
Collections.addAll(list1, "张老三,23", "李四,24", "王老五,25", "赵老六,26", "钱七,27", "孙老八,28");
Collections.addAll(list2, "杨幂,18", "王祖贤,18", "杨超越,18", "杨紫,18", "宋茜,18", "倪妮,18");
Stream<String> stream1 = list1.stream().filter(s -> s.split(",")[0].length() == 3)
.limit(2);//张老三,23 王老五,25
Stream<String> stream2 = list2.stream().filter( s-> s.split(",")[0].startsWith("杨"))
.skip(1);//杨超越,18 杨紫,18
List<Actor> list = 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]);
Actor a = new Actor(name, age);
return a;
}
}).collect(Collectors.toList());
System.out.println(list);
//也可以用Lambda简写
/*Stream.concat(stream1,stream2)
.map(s ->new Actor(s.split(",")[0] , Integer.parseInt(s.split(",")[1]) ) );
*/
[Actor{name = 张老三, age = 23}, Actor{name = 王老五, age = 25}, Actor{name = 杨超越, age = 18},Actor{name = 杨紫, age = 18}]