public class Test {
// 方法作用: 按照步骤将字符串转换
// 参数: 被转换的字符串, 转换方式1, 转换方式2, 转换方式3
public static int change(String s, Function<String, String> fun1, Function<String, Integer> fun2, Function<Integer, Integer> fun3) {
return fun1.andThen(fun2).andThen(fun3).apply(s);
}
public static void main(String[] args) {
String str = "赵丽颖,20";
// 匿名内部类方式
int num1 = change(
str,
new Function<String, String>() { // 将字符串截取数字年龄部分, 得到字符串
@Override
public String apply(String s) {
return s.split(",")[1];
}
},
new Function<String, Integer>() { // 将上一步的字符串转换成为int类型的数字
@Override
public Integer apply(String s) {
return Integer.parseInt(s);
}
},
new Function<Integer, Integer>() { // 将上一步的int数字累加100, 得到结果int数字
@Override
public Integer apply(Integer integer) {
return integer + 100;
}
}
);
System.out.println(num1);
// Lambda方式
int num2 = change(
str,
s -> s.split(",")[1],
s -> Integer.parseInt(s),
i -> i + 100
);
System.out.println(num2);
}
}
package StreamFilterTest;
import java.util.stream.Stream;
public class StreamFilter {
public static void main(String[] args) {
String[] str= {"张三丰","张翠山","张无忌","赵敏","铁蛋"};
Stream<String> str1 = Stream.of(str);
Stream<String> str2 = str1.filter((String name) -> {
return name.startsWith("张");
});
str2.forEach((String name)->{
System.out.println(name);
});
Stream.of("张三丰","张翠山","张无忌","赵敏","铁蛋")
.filter( name-> name.startsWith("张"))
.forEach(name->System.out.println(name));
}
}
package StreamMap;
import java.util.stream.Stream;
public class Test {
public static void main(String[] args) {
Stream<String> stream = Stream.of("1", "2", "3", "4", "5");
Stream<Integer> stream1 = stream.map( i-> Integer.parseInt(i));
stream1.forEach(integer->System.out.println(integer));
Stream.of("1", "2", "3", "4", "5")
.map(string->Integer.parseInt(string))
.forEach(i-> System.out.println(i));
}
}
package StreamLimit;
import java.util.stream.Stream;
public class Test {
public static void main(String[] args) {
String[] str= {"铁锤","铁柱","铁球","铁饼","铁蛋"};
Stream<String> str1 = Stream.of(str);
Stream<String> limit = str1.limit(2);
limit.forEach((String name)->{
System.out.println(name);
});
System.out.println("*********");
Stream.of("铁锤","铁蛋","铁柱")
.limit(5)//limit(-1) IllegalArgumentException: -1
.forEach(name-> System.out.println(name));
System.out.println("********");
Stream.of("铁棒","铁球","铁柱")
.limit(2)
.skip(1)
.forEach(name-> System.out.println(name));
}
}
package StreamSkip;
import java.util.stream.Stream;
public class Test {
public static void main(String[] args) {
String[] str= {"琦玉","银时","犬夜叉","三上悠雅","迪迦"};
Stream<String> stream = Stream.of(str);
Stream<String> stream1 = stream.skip(3);
stream1.forEach(name-> System.out.println(name));
System.out.println("*****************");
Stream.of(str)
.skip(4)
.skip(-1)//返回 IllegalArgumentException: -1
.skip(9)//返回一个空的流
.forEach(name-> System.out.println(name));
}
}
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) | 黑马程序员IT技术论坛 X3.2 |