Given the code fragments:
class TechName {
String techName;
TechName(String techName) {
this.techName = techName;
}
}
and
List<TechName> tech = Arrays.asList(
new TechName("Java-"),
new TechName("Oracle DB-"),
new TechName("J2EE-")
);
Stream<TechName> stre = tech.stream();
//line n1
Which should be inserted at line n1 to print Java-Oracle DB-J2EE-?
A.
stre.forEach(System.out::print);
B.
stre.map(a -> a.techName).forEach(System.out::print);
C.
stre.map(a -> a).forEachOrdered(System.out::print);
D.
stre.forEachOrdered(System.out::print);
题解
选项 A,由于 TechName 类别没有覆写 toString 方法,因此无法直接输出 techName 字段的值,而是输出最上层 Object 类别的 toString 方法所产生出来的字符串。
选项 B,利用 Stream 对象的 map 方法去替换 Stream 对象的元素为 TechName 对象的 techName 字段值,之后再使用 forEach 方法将 techName 字段值输出,可得到题目要的输出结果。
选项 C,无法直接输出 techName 字段的值,理由同选项 A。可以改成以下程序,即可得到正确结果:
stre.map(a -> a.techName).forEachOrdered(System.out::print);
选项 D,无法直接输出 techName 字段的值,理由同选项 A。
