//FullName(String name, String fullName)
List<FullName> fullNameList = Arrays.asList(
new FullName("Alpha", "Alpha Maz"),
new FullName("Beta", "Beta Sew"),
new FullName("Delta", "Delta Non"),
new FullName("Indigo", "Indigo Loe")
);
List<String> nameList = Arrays.asList(new String[] {"Delta","Alpha"});
让我们以上面的示例列表为例。我想将nameList与fullNameList进行比较,如果找到匹配项,则返回全名。
我必须使用nameList作为主要对象,因为我希望结果遵循nameList中的顺序,所以我不知道如何从比较列表(fullNameList)中“收集”元素
String result= nameList.stream()
.filter(v -> fullNameList.stream().anyMatch(s -> s.getName().equals(v)))
.collect(Collectors.joining(","));
Actual Result : "Delta,Alpha"
Expected Result : "Delta Non,Alpha Maz"
任何想法如何使用Java 8 Stream吗?
为了将短名称映射到相应的全名,您需要使用map
而不是filter
。>
String result=
nameList.stream()
.map(v -> fullNameList.stream()
.filter(s -> s.getName().equals(v))
.findFirst()
.map(FullName::getFullName))
.filter(Optional::isPresent)
.map(Optional::get)
.collect(Collectors.joining(","));