1.Java8 Arrays.stream和Stream.of 获取一个Stream
对于对象数组,两者都调用相同的 Arrays.stream 方法,直接返回对应的流对象
String[] array = {“a”, “b”, “c”, “d”, “e”};
Stream stream = Arrays.stream(array);
Stream stream1 = Stream.of(array);
对于基本数组,Stream.of返回的流不能直接遍历输出或操作,需要先转换为 IntStream
int[] intArray = {1, 2, 3, 4, 5};
IntStream stream = Arrays.stream(intArray);
Stream<int[]> temp = Stream.of(intArray);
// 不能直接输出,需要先转换为 IntStream
IntStream intStream = temp.flatMapToInt(x -> Arrays.stream(x));
数组转换成流推荐使用Arrays.stream。
Stream.of(T... values);支持任意类型,像一把万能锁,可以把T转换为Stream<T>(其中对象数组T[]会转换为Stream<T>)
/**
* Returns a sequential {@code Stream} containing a single element.
*
* @param t the single element
* @param <T> the type of stream elements
* @return a singleton sequential stream
*/
public static<T> Stream<T> of(T t) {
return StreamSupport.stream(new Streams.StreamBuilderImpl<>(t), false);
}
综上
数组转流使用 Arrays.stream(数组);
集合转流使用 集合.stream();
单个对象转流使用 Stream.of(单个对象);
https://blog.csdn.net/yyytttmm/article/details/108206853
2.stream().map()方法详解
map方法类似一个迭代器,对调用这个Stream.map(**)的对象进行lambda表达式操作
https://blog.csdn.net/qq_41135605/article/details/109494073
3.Stream.concat()合并两个或多个stream
Stream合并与去重
http://www.leftso.com/blog/613.html
public static void main(String[] args)
{
//两个Stream合并
Stream<Integer> firstStream = Stream.of(1, 2, 3);
Stream<Integer> secondStream = Stream.of(4, 5, 6);
Stream<Integer> resultingStream = Stream.concat(firstStream, secondStream);
//多个Stream合并
Stream<Integer> first = Stream.of(1, 2);
Stream<Integer> second = Stream.of(3,4);
Stream<Integer> third = Stream.of(5, 6);
Stream<Integer> fourth = Stream.of(7,8);
Stream<Integer> resultingStream = Stream.concat(first, concat(second, concat(third, fourth)));
//基础类型去重
Stream<Integer> firstStream = Stream.of(1, 2, 3, 4, 5, 6);
Stream<Integer> secondStream = Stream.of(4, 5, 6, 7, 8, 9);
Stream<Integer> resultingStream = Stream.concat(firstStream, secondStream)
.distinct();
//自定义对象去重
Stream<Employee> stream1 = getEmployeeListOne().stream();
Stream<Employee> stream2 = getEmployeeListTwo().stream();
Stream<Employee> resultingStream = Stream.concat(stream1, stream2)
.filter(distinctByKey(Employee::getFirstName));
}
4.Class
//T.getClass().getDeclaredFields() 返回类所有字段的类型对象数组,这包括public、protected、default、private字段,但不包括继承的字段。
//T.getClass().getFields(); 返回所有的public字段的类型对象数组,包括父类中的字段