JDK lambda表达式
基本使用方法
1. 无参,如定义一个线程,可以简写为
new Thread(() -> System.out.print("运行")).start();
2. 有参数
Collections.sort(list, (o1, o2) -> return o1.compareTo(o2));
3. 类型改变 && 方法调用
public class Demo {
@Test
public void test02() {
List<Integer> intList = new ArrayList<>();
intList.add(1);
intList.add(2);
intList.add(3);
intList.add(4);
List<String> stringList = intList.stream().map(x -> String.valueOf(x)).collect(Collectors.toList());
stringList.forEach(System.out::println);
}
}
4. List转Map
public class Demo {
@Test
public void test03() {
List<Integer> intList = new ArrayList<>();
intList.add(1);
intList.add(2);
intList.add(3);
intList.add(4);
Map<Integer, String> stringMap = intList.stream().collect(Collectors.toMap(x -> x, x -> "数据为:" + String.valueOf(x)));
stringMap.entrySet().forEach(x-> System.out.println(x.getKey() + "\t" + x.getValue()));
}
}
5. Filter
public class Demo {
@Test
public void test03() {
List<Integer> intList = new ArrayList<>();
intList.add(1);
intList.add(2);
intList.add(3);
intList.add(4);
Map<Integer, String> stringMap = intList.stream().filter(x -> x > 2 ).collect(Collectors.toMap(x -> x, x -> "数据为:" + String.valueOf(x)));
stringMap.entrySet().forEach(x-> System.out.println(x.getKey() + "\t" + x.getValue()));
}
}
6. groupBy
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class DemoTest {
@Test
public void test04() {
List<User> userList = new ArrayList<>();
userList.add(new User(1, "力宏"));
userList.add(new User(2, "张力"));
userList.add(new User(1, "虚仓"));
userList.add(new User(3, "君太"));
Map<Integer, List<User>> collect = userList.stream().collect(Collectors.groupingBy(x -> x.getGroupId()));
collect.entrySet().forEach(x -> System.out.println("组: " + x.getKey() + "\t成员:" + x.getValue()));
}
public class User {
private Integer groupId;
private String name;
public User(Integer id, String name) {
this.groupId = id;
this.name = name;
}
public Integer getGroupId() {
return groupId;
}
public void setGroupId(Integer groupId) {
this.groupId = groupId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "User{" +
"groupId=" + groupId +
", name='" + name + '\'' +
'}';
}
}
}
7. Predicate
public class DemoTest {
@Test
public void test05() {
List<Integer> intList = new ArrayList<>();
intList.add(1);
intList.add(2);
intList.add(3);
intList.add(4);
Predicate<Integer> predicate = (n) -> n % 2 == 0;
intList.forEach(x -> {
if(predicate.test(x)) {
System.out.println("偶数:" + x);
}
});
}
}
8. @FunctionalInterface
public class DemoTest {
@Test
public void test06() {
List<Worker> workers = new ArrayList<>();
workers.add(()-> {
System.out.println("打工1");
});
workers.add(()-> {
System.out.println("打工2");
});
workers.add(()-> {
System.out.println("打工3");
});
workers.forEach(Worker::work);
}
@FunctionalInterface
public interface Worker {
void work();
}
}