jdk8引入了lambda表达式和stream,用起来还是很舒服的,记录一下常见的几种用法
1、forEach
public class ForEachMain {
public static void main(String[] args) {
//简单的打印,两段代码的功能相同
new ArrayList<>().forEach(System.out::println);
new ArrayList<>().forEach(i-> System.out.println(i));
new HashMap<>().forEach((k,v)-> {
System.out.println(k);
System.out.println(v);
});
//下面两段代码功能相同
IntStream.range(0,10000).forEach(i-> System.out.println(i));
for (int i = 0; i < 10000; i++) {
System.out.println(i);
}
}
}
2、map
将流中的所有对象,根据一个函数转换成另外一种对象
public class MapMain {
public static void main(String[] args) {
List<String> stringList = new ArrayList<>();
List<Integer> intList = stringList.stream().map(Integer::valueOf).collect(Collectors.toList());
}
}
3、groupBy
将流中的所有对象,按照一个函数获取key分组形成一个map
public class GroupByMain {
public static void main(String[] args) {
List<A> aList = new ArrayList<>();
aList.add(new A("1", "first"));
aList.add(new A("2", "second"));
aList.add(new A("1", "third"));
Map<String, List<A>> aMap = aList.stream().collect(Collectors.groupingBy(A::getVersion));
System.out.println(aMap);
}
}
//{1=[{"version":"1","name":"first"}, {"version":"1","name":"third"}], 2=[{"version":"2","name":"second"}]}
4、map
将流中的所有元素,根据一个函数得到key,再根据一个函数得到value,形成一个map
public static void main(String[] args) {
List<Thread> threads = new ArrayList<>();
threads.add(new Thread("thread1"));
threads.add(new Thread("thread2"));
threads.add(new Thread("thread3"));
//线程名-线程对象的map
Map<String, Thread> threadMap = threads.stream().collect(Collectors.toMap(Thread::getName, Function.identity()));
//线程名-线程对象的map另一种写法
Map<String, Thread> threadMap1 = threads.stream().collect(Collectors.toMap(Thread::getName, i -> i));
//线程名-线程id的map
Map<String, Long> threaNameAndIdMap = threads.stream().collect(Collectors.toMap(Thread::getName, Thread::getId));
}