lambda表达式的简单实现

来源:互联网 发布:luaeditor mac 编辑:程序博客网 时间:2024/05/21 21:46

Java 8的一个大亮点是引入Lambda表达式,使用它设计的代码会更加简洁。当开发者在编写Lambda表达式时,也会随之被编译成一个函数式接口。下面这个例子就是使用Lambda语法来代替匿名的内部类,代码不仅简洁,而且还可读。
没有使用Lambda的老方法:
1
 
1
2
3
4
5
button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae){
System.out.println("Actiondetected");
}
});
使用Lambda:
1
2
3
button.addActionListener(()->{ 
System.out.println("Actiondetected");
});
让我们来看一个更明显的例子。
不采用Lambda的老方法:




Runnable runnable1=new Runnable(){
@Override
public void run(){
System.out.println("RunningwithoutLambda");
}
};
使用Lambda:
1
2
3
Runnable runnable2=()->{
System.out.println("RunningfromLambda");
};
正如你所看到的,使用Lambda表达式不仅让代码变的简单、而且可读、最重要的是代码量也随之减少很多。然而,在某种程度上,这些功能在Scala等这些JVM语言里已经被广泛使用。
并不奇怪,Scala社区是难以置信的,因为许多Java 8里的内容看起来就像是从Scala里搬过来的。在某种程度上,Java 8的语法要比Scala的更详细但不是很清晰,但这并不能说明什么,如果可以,它可能会像Scala那样构建Lambda表达式。
一方面,如果Java继续围绕Lambda来发展和实现Scala都已经实现的功能,那么可能就不需要Scala了。另一方面,如果它只提供一些核心的功能,例如帮助匿名内部类,那么Scala和其他语言将会继续茁壮成长,并且有可能会凌驾于Java之上。其实这才是最好的结果,有竞争才有进步,其它语言继续发展和成长,并且无需担心是否会过时。
接下来我就给大家简单的来实现一下lambda表达式吧,首先我们得在项目APP中bulid.grade中的android{}中添加 compileOptions{
        //设置JDK1.8
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8


    }

然后在defaultconfig中添加jackOptions {
            enabled true
        }

然后在根目录中添加

 classpath 'me.tatarka:gradle-retrolambda:3.2.0'

这就好了然后直接上代码

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical"    tools:context="com.example.lamadas.MainActivity">    <Button        android:id="@+id/btn1"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="转换为小写"        />    <Button        android:id="@+id/btn2"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="转为平方数"        />    <Button        android:id="@+id/btn3"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="合并集合,并遍历"        />    <Button        android:id="@+id/btn4"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="筛选偶数"        />    <Button        android:id="@+id/btn5"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="转为大写"        /></LinearLayout>
这是main中的

import android.os.Bundle;import android.support.v7.app.AppCompatActivity;import android.view.View;import android.widget.Button;import java.util.Arrays;import java.util.List;import java.util.stream.Collectors;import java.util.stream.Stream;public class MainActivity extends AppCompatActivity {    Button btn1,btn2,btn3,btn4,btn5;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        btn1= (Button) findViewById(R.id.btn1);        btn2= (Button) findViewById(R.id.btn2);        btn3= (Button) findViewById(R.id.btn3);        btn4= (Button) findViewById(R.id.btn4);        btn5= (Button) findViewById(R.id.btn5);        btn1.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                List<String> wordList=  Arrays.asList("PPPPPPPPPP=====","HHHHHHH======","ooooo====");                List<String> output =                        wordList.stream()//                                .map(String::toLowerCase)                                .collect(Collectors.toList());                //这段代码把所有的单词转换为小写。                System.out.println(output+"======单词转换为小写====");                System.out.println("=================================================================");            }        });btn2.setOnClickListener(new View.OnClickListener() {    @Override    public void onClick(View v) {        //平方数        List<Integer> nums = Arrays.asList(1, 2, 3, 4);        List<Integer> squareNums =                nums.stream()                        .map(n -> n * n)                        .collect(Collectors.toList());//这段代码生成一个整数 list 的平方数 {1, 4, 9, 16}。        System.out.println(squareNums+"=====整数 list 的平方数=====");        System.out.println("=================================================================");    }});btn3.setOnClickListener(new View.OnClickListener() {    @Override    public void onClick(View v) {        Stream<List<Integer>> inputStream = Stream.of(                Arrays.asList(1),                Arrays.asList(2, 3),                Arrays.asList(4, 5, 6)        );        Stream<Integer> outputStream = inputStream.flatMap((childList) -> childList.stream());        // flatMap合并集合,并且遍        outputStream.forEach(System.out::println);        System.out.println("=================================================================");    }});btn4.setOnClickListener(new View.OnClickListener() {    @Override    public void onClick(View v) {        // filter 对原始 Stream 进行筛选,筛选偶数        Integer[] sixNums = {1, 2, 3, 4, 5, 6};        Integer[] evens = Stream.of(sixNums)                .filter(n -> n%2 == 0)                .toArray(Integer[]::new);        System.out.println("---------筛选偶数------");//        打印        Arrays.stream(evens).forEach(System.out::println);        System.out.println("=================================================================");    }});btn5.setOnClickListener(new View.OnClickListener() {    @Override    public void onClick(View v) {        Stream.of("one", "two", "three", "four")                .filter(e -> e.length() > 3)//筛选字母个数大于3的                .peek(e -> System.out.println("Filtered value: " + e))                .map(String::toUpperCase)//转大写                .peek(e -> System.out.println("Mapped value: " + e))                .collect(Collectors.toList());        System.out.println("=================================================================");    }});    }}

这就是全部的代码 了




原创粉丝点击