/**
*
*/
package com.lambdasTest.stream;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.function.BinaryOperator;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* jdk8 lambda 函数式编程之stream
*
* @Date Oct 23, 2017 12:27:17 PM
*/
public class StreamOfLambdas {
public static void main(String[] agrs) {
// collect(toList())
List<String> collected = Stream.of("a", "b", "c", "d").collect(Collectors.toList());
System.out.println(collected); // [a, b, c, d]
System.out.println(Arrays.asList("a", "b", "c", "d")); //[a, b, c, d]
// map 将一个流中的值转换成一个新的流
collected = Stream.of("a", "b", "hEllo").map(string -> string.toUpperCase()).collect(Collectors.toList());
System.out.println(collected); // [A,B,HELLO]
// filter
List<String> beginningWithNumbers = Stream.of("a", "1abc", "5acs").filter(value -> isDigit(value.charAt(0))).collect(Collectors.toList());
System.out.println("filter: " + beginningWithNumbers); // [1abc, 5acs]
// flatmap 可用Stream替换值,然后将多个Stream连接成一个Stream
List<Integer> together = Stream.of(Arrays.asList(1, 2), Arrays.asList(3, 4)).flatMap(numbers -> numbers.stream()).collect(Collectors.toList());
System.out.println(together); // [1, 2, 3, 4]
// min and max
List<Track> tracks = Arrays.asList(new Track("bakai", 524), new Track("Vlolets for your furs", 373), new Track("Time was", 451));
Track shortestTrack = tracks.stream().min(Comparator.comparing(track->track.getLength())).get();
System.out.println(shortestTrack.getName().toString() + shortestTrack.getLength()); // Vlolets for your furs373
// reduce 从一组值中生成一个值
int count = Stream.of(1, 2, 3).reduce(0, (acc, element) -> acc + element);
System.out.println(count); //6
BinaryOperator<Integer> accumulator = (acc, element) -> acc + element;
count = accumulator.apply(accumulator.apply(accumulator.apply(0, 1), 2), 3);
System.out.println(count); //6
}
public static boolean isDigit(char c) {
return (int) c >= 48 && (int) c <= 57;
}
}
class Track {
private String name;
private int length;
/**
* @param name
* 曲目
* @param length
* 长度
*/
public Track(final String name, final int length) {
super();
this.name = name;
this.length = length;
}
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name
* the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* @return the length
*/
public int getLength() {
return length;
}
/**
* @param length
* the length to set
*/
public void setLength(int length) {
this.length = length;
}
}
jdk8 lambda 常用流操作
最新推荐文章于 2024-04-30 04:48:02 发布