泛型,泛型是在运行时才能确定的类型
看下面的例子,我们List的泛型是确定的,所以Collection和Stream的泛型也是确定的,Stream里面的T是我们输入流的类型,这里使用了lambda表达式,传入了一个方法。
重点看这里的map方法,接口里面的定义。
String languages = messageTemplates
.stream()
.map(MessageTemplateDTO::getChoiceLang)
.collect(Collectors.joining(","));
public interface Collection<E> extends Iterable<E> {
/**
* Returns a sequential {@code Stream} with this collection as its source.
*
* <p>This method should be overridden when the {@link #spliterator()}
* method cannot return a spliterator that is {@code IMMUTABLE},
* {@code CONCURRENT}, or <em>late-binding</em>. (See {@link #spliterator()}
* for details.)
*
* @implSpec
* The default implementation creates a sequential {@code Stream} from the
* collection's {@code Spliterator}.
*
* @return a sequential {@code Stream} over the elements in this collection
* @since 1.8
*/
default Stream<E> stream() {
return StreamSupport.stream(spliterator(), false);
}
}
public interface Stream<T> extends BaseStream<T, Stream<T>> {
/**
* Returns a stream consisting of the results of applying the given
* function to the elements of this stream.
*
* <p>This is an <a href="package-summary.html#StreamOps">intermediate
* operation</a>.
*
* @param <R> The element type of the new stream
* @param mapper a <a href="package-summary.html#NonInterference">non-interfering</a>,
* <a href="package-summary.html#Statelessness">stateless</a>
* function to apply to each element
* @return the new stream
*/
<R> Stream<R> map(Function<? super T, ? extends R> mapper);
}
/**
* Represents a function that accepts one argument and produces a result.
*
* <p>This is a <a href="package-summary.html">functional interface</a>
* whose functional method is {@link #apply(Object)}.
*
* @param <T> the type of the input to the function
* @param <R> the type of the result of the function
*
* @since 1.8
*/
@FunctionalInterface
public interface Function<T, R> {
/**
* Applies this function to the given argument.
*
* @param t the function argument
* @return the function result
*/
R apply(T t);
}
这一句里面,第一个代表是个泛型接口,不确定的类型是R,因为这里T的类型在定义的时候已经确定下来了,Stream代表返回值,? super T 表示是T类型或者它的父类,? extends R 指这里是R类型或者其子类。
具体来说,这里的Function<T, R>,T代表方法的调用类,R代表方法的返回类
<R> Stream<R> map(Function<? super T, ? extends R> mapper);
由于传入的是MessageTemplateDTO::getChoiceLang这样一个方法,那么就能确定下来返回的是String类型,即R的类型,这个是编译的时候确定的