if…else…在代码中经常使用,听说可以通过Java 8的Function接口来消灭if…else…!Function接口是什么?如果通过Function接口接口消灭if…else…呢?让我们一起来探索一下吧。
Function接口就是一个有且仅有一个抽象方法,但是可以有多个非抽象方法的接口,Function接口可以被隐式转换为 lambda 表达式。可以通过FunctionalInterface注解来校验Function接口的正确性。Java 8允许在接口中加入具体方法。接口中的具体方法有两种,default方法和static方法。
@FunctionalInterface
interface TestFunctionService
{
void addHttp(String url);
}
那么就可以使用Lambda表达式来表示该接口的一个实现。
TestFunctionService testFunctionService = url -> System.out.println("http:" + url);
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface FunctionalInterface {}
上图是FunctionalInterface的注解说明。通过上面的注解说明,可以知道FunctionalInterface是一个注解,用来说明一个接口是函数式接口。 函数式接口只有一个抽象方法。 可以有默认方法,因为默认方法有一个实现,所以不是抽象的。函数接口的实例可以用lambda表达式、方法引用或构造函数引用创建。
FunctionalInterface会校验接口是否满足函数式接口:
编译器会将满足函数式接口定义的任何接口视为函数式接口,而不管该接口声明中是否使用FunctionalInterface注解。
Function接口主要分类:
Function函数的表现形式为接收一个参数,并返回一个值。
@FunctionalInterface
public interface Function<T, R> {
R apply(T t);
default <V> Function<V, R> compose(Function<? super V, ? extends T> before) {
Objects.requireNonNull(before);
return (V v) -> apply(before.apply(v));
}
default <V> Function<T, V> andThen(Function<? super R, ? extends V> after) {
Objects.requireNonNull(after);
return (T t) -> after.apply(apply(t));
}
static <T> Function<T, T> identity() {
return t -> t;
}
}
1)apply
测试代码:
public String upString(String str){
Function<String, String> function1 = s -> s.toUpperCase();
return function1.apply(str);
}
public static void main(String[] args) {
System.out.println(upString("hello!"));
}
通过apply调用具体的实现。执行结果:
2)compose
测试代码:
public static void main(String[] args) {
Function<String, String> function1 = s -> s.toUpperCase();
Function<String, String> function2 = s -> "my name is "+s;
String result = function1.compose(function2).apply("zhangSan");
System.out.println(result);
}
执行结果
如结果所示:compose 先执行function2 后执行function1。
3)andThen
测试代码:
public static void main(String[] args) {
Function<String, String> function1 = s -> s.toUpperCase();
Function<String, String> function2 = s -> "my name is "+s;
String result = function1.andThen(function2).apply("zhangSan");
System.out.println(result);
}
执行结果:
如结果所示:
andThen先执行function1 后执行function2。
测试代码:
public static void main(String[] args) {
Stream<String> stream = Stream.of("order", "good", "lab", "warehouse");
Map<String, Integer> map = stream.collect(Collectors.toMap(Function.identity(), String::length));
System.out.println(map);
}
执行结果:
Supplier的表现形式为不接受参数、只返回数据。
@FunctionalInterface
public interface Supplier<T> {
/**
* Gets a result.
*
* @return a result
*/
T get();
}
get:抽象方法。通过实现返回T。
public class SupplierTest {
SupplierTest(){
System.out.println(Math.random());
System.out.println(this.toString());
}
}
public static void main(String[] args) {
Supplier<SupplierTest> sup = SupplierTest::new;
System.out.println("调用一次");
sup.get();
System.out.println("调用二次");
sup.get();
}
执行结果:
如结果所示:Supplier建立时并没有创建新类,每次调用get返回的值不是同一个。
Consumer接收一个参数,没有返回值。
@FunctionalInterface
public interface Consumer<T> {
void accept(T t);
default Consumer<T> andThen(Consumer<? super T> after) {
Objects.requireNonNull(after);
return (T t) -> { accept(t); after.accept(t); };
}
}
public static void main(String[] args) {
Consumer<String> consumer = s -> System.out.println("consumer_"+s);
Consumer<String> after = s -> System.out.println("after_"+s);
consumer.accept("isReady");
System.out.println("========================");
consumer.andThen(after).accept("is coming");
}
执行结果:
如结果所示:对同一个参数T,通过andThen 方法,先执行consumer,再执行fater。
Runnable:Runnable的表现形式为即没有参数也没有返回值。
@FunctionalInterface
public interface Runnable {
public abstract void run();
}
run:抽象方法。run方法实现具体的内容,需要将Runnale放入到Thread中,通过Thread类中的start()方法启动线程,执行run中的内容。
public class TestRun implements Runnable {
@Override
public void run() {
System.out.println("TestRun is running!");
}
}
public static void main(String[] args) {
Thread thread = new Thread(new TestRun());
thread.start();
}
执行结果:
如结果所示:当线程实行start方法时,执行Runnable 的run方法中的内容。
Function的主要用途是可以通过lambda 表达式实现方法的内容。
原代码:
@Data
public class User {
/**
* 姓名
*/
private String name;
/**
* 年龄
*/
private int age;
/**
* 组员
*/
private List<User> parters;
}
public static void main(String[] args) {
User user =new User();
if(user ==null ||user.getAge() <18 ){
throw new RuntimeException("未成年!");
}
}
执行结果:
使用Function接口后的代码:
@FunctionalInterface
public interface testFunctionInfe {
/**
* 输入异常信息
* @param message
*/
void showExceptionMessage(String message);
}
public static testFunctionInfe doException(boolean flag){
return (message -> {
if (flag){
throw new RuntimeException(message);
}
});
}
public static void main(String[] args) {
User user =new User();
doException(user ==null ||user.getAge() <18).showExceptionMessage("未成年!");
}
执行结果:
使用function接口前后都抛出了指定的异常信息。
原代码:
public static void main(String[] args) {
User user =new User();
if(user==null){
System.out.println("新增用户");
}else {
System.out.println("更新用户");
}
}
使用Function接口后的代码:
public static void main(String[] args) {
User user =new User();
Consumer trueConsumer = o -> {
System.out.println("新增用户");
};
Consumer falseConsumer= o -> {
System.out.println("更新用户");
};
trueOrFalseMethdo(user).showExceptionMessage(trueConsumer,falseConsumer);
}
public static testFunctionInfe trueOrFalseMethdo(User user){
return ((trueConsumer, falseConsumer) -> {
if(user==null){
trueConsumer.accept(user);
}else {
falseConsumer.accept(user);
}
});
}
@FunctionalInterface
public interface testFunctionInfe {
/**
* 不同分处理不同的事情
* @param trueConsumer
* @param falseConsumer
*/
void showExceptionMessage(Consumer trueConsumer,Consumer falseConsumer);
}
执行结果:
原代码:
public static void main(String[] args) {
String flag="";
if("A".equals(flag)){
System.out.println("我是A");
}else if ("B".equals(flag)) {
System.out.println("我是B");
}else if ("C".equals(flag)) {
System.out.println("我是C");
}else {
System.out.println("没有对应的指令");
}
}
使用Function接口后的代码:
public static void main(String[] args) {
String flag="B";
Map<String, Runnable> map =initFunctionMap();
trueOrFalseMethdo(map.get(flag)==null).showExceptionMessage(()->{
System.out.println("没有相应指令");
},map.get(flag));
}
public static Map<String, Runnable> initFunctionMap(){
Map<String,Runnable> result = Maps.newHashMap();
result.put("A",()->{System.out.println("我是A");});
result.put("B",()->{System.out.println("我是B");});
result.put("C",()->{System.out.println("我是C");});
return result;
}
public static testFunctionInfe trueOrFalseMethdo(boolean flag){
return ((runnable, falseConsumer) -> {
if(flag){
runnable.run();
}else {
falseConsumer.run();
}
});
}
执行结果:
Function函数式接口是java 8新加入的特性,可以和lambda表达式完美结合,是非常重要的特性,可以极大的简化代码。
我有一个字符串input="maybe(thisis|thatwas)some((nice|ugly)(day|night)|(strange(weather|time)))"Ruby中解析该字符串的最佳方法是什么?我的意思是脚本应该能够像这样构建句子:maybethisissomeuglynightmaybethatwassomenicenightmaybethiswassomestrangetime等等,你明白了......我应该一个字符一个字符地读取字符串并构建一个带有堆栈的状态机来存储括号值以供以后计算,还是有更好的方法?也许为此目的准备了一个开箱即用的库?
很好奇,就使用rubyonrails自动化单元测试而言,你们正在做什么?您是否创建了一个脚本来在cron中运行rake作业并将结果邮寄给您?git中的预提交Hook?只是手动调用?我完全理解测试,但想知道在错误发生之前捕获错误的最佳实践是什么。让我们理所当然地认为测试本身是完美无缺的,并且可以正常工作。下一步是什么以确保他们在正确的时间将可能有害的结果传达给您? 最佳答案 不确定您到底想听什么,但是有几个级别的自动代码库控制:在处理某项功能时,您可以使用类似autotest的内容获得关于哪些有效,哪些无效的即时反馈。要确保您的提
我主要使用Ruby来执行此操作,但到目前为止我的攻击计划如下:使用gemsrdf、rdf-rdfa和rdf-microdata或mida来解析给定任何URI的数据。我认为最好映射到像schema.org这样的统一模式,例如使用这个yaml文件,它试图描述数据词汇表和opengraph到schema.org之间的转换:#SchemaXtoschema.orgconversion#data-vocabularyDV:name:namestreet-address:streetAddressregion:addressRegionlocality:addressLocalityphoto:i
我正在使用ruby1.9解析以下带有MacRoman字符的csv文件#encoding:ISO-8859-1#csv_parse.csvName,main-dialogue"Marceu","Giveittohimóhe,hiswife."我做了以下解析。require'csv'input_string=File.read("../csv_parse.rb").force_encoding("ISO-8859-1").encode("UTF-8")#=>"Name,main-dialogue\r\n\"Marceu\",\"Giveittohim\x97he,hiswife.\"\
简而言之错误:NOTE:Gem::SourceIndex#add_specisdeprecated,useSpecification.add_spec.Itwillberemovedonorafter2011-11-01.Gem::SourceIndex#add_speccalledfrom/opt/local/lib/ruby/site_ruby/1.8/rubygems/source_index.rb:91./opt/local/lib/ruby/gems/1.8/gems/rails-2.3.8/lib/rails/gem_dependency.rb:275:in`==':und
导读:随着叮咚买菜业务的发展,不同的业务场景对数据分析提出了不同的需求,他们希望引入一款实时OLAP数据库,构建一个灵活的多维实时查询和分析的平台,统一数据的接入和查询方案,解决各业务线对数据高效实时查询和精细化运营的需求。经过调研选型,最终引入ApacheDoris作为最终的OLAP分析引擎,Doris作为核心的OLAP引擎支持复杂地分析操作、提供多维的数据视图,在叮咚买菜数十个业务场景中广泛应用。作者|叮咚买菜资深数据工程师韩青叮咚买菜创立于2017年5月,是一家专注美好食物的创业公司。叮咚买菜专注吃的事业,为满足更多人“想吃什么”而努力,通过美好食材的供应、美好滋味的开发以及美食品牌的孵
一、引擎主循环UE版本:4.27一、引擎主循环的位置:Launch.cpp:GuardedMain函数二、、GuardedMain函数执行逻辑:1、EnginePreInit:加载大多数模块int32ErrorLevel=EnginePreInit(CmdLine);PreInit模块加载顺序:模块加载过程:(1)注册模块中定义的UObject,同时为每个类构造一个类默认对象(CDO,记录类的默认状态,作为模板用于子类实例创建)(2)调用模块的StartUpModule方法2、FEngineLoop::Init()1、检查Engine的配置文件找出使用了哪一个GameEngine类(UGame
我正在使用ruby2.1.0我有一个json文件。例如:test.json{"item":[{"apple":1},{"banana":2}]}用YAML.load加载这个文件安全吗?YAML.load(File.read('test.json'))我正在尝试加载一个json或yaml格式的文件。 最佳答案 YAML可以加载JSONYAML.load('{"something":"test","other":4}')=>{"something"=>"test","other"=>4}JSON将无法加载YAML。JSON.load("
我认为我的问题最好用一个例子来描述。假设我有一个名为“Thing”的简单模型,它有一些简单数据类型的属性。像...Thing-foo:string-goo:string-bar:int这并不难。数据库表将包含具有这三个属性的三列,我可以使用@thing.foo或@thing.bar之类的东西访问它们。但我要解决的问题是当“foo”或“goo”不再包含在简单数据类型中时会发生什么?假设foo和goo代表相同类型的对象。也就是说,它们都是“Whazit”的实例,只是数据不同。所以现在事情可能看起来像这样......Thing-bar:int但是现在有一个新的模型叫做“Whazit”,看起来
我有一个要在我的Rails3项目中使用的数组扩展方法。它应该住在哪里?我有一个应用程序/类,我最初把它放在(array_extensions.rb)中,在我的config/application.rb中我加载路径:config.autoload_paths+=%W(#{Rails.root}/应用程序/类)。但是,当我转到railsconsole时,未加载扩展。是否有一个预定义的位置可以放置我的Rails3扩展方法?或者,一种预先定义的方式来添加它们?我知道Rails有自己的数组扩展方法。我应该将我的添加到active_support/core_ext/array/conversion