我需要改变代码如下:
protected void checkNoDuplicateLabels( List<CompileResult> compileResult ) {
Set<Label> infos = new HashSet<>();
for ( AbstractTypeInfo info : infoRepo.getList() ) {
if ( info instanceof Label ) {
Label label = (Label) info;
if ( infos.contains( label ) ) {
compileResult.add( new CompileResult( Severity.FATAL, MessageFormat.format( "Duplicate label found! \n Type: '{0}' \n Language: '{1}'", label.getType(), label.getLanguage() ) ) );
}
infos.add( label );
}
}
}
成流。我知道,使用设置有流的一个方法是通过实施AtomicReferences,将取代方法的第一行到这一点:
AtomicReference<Set<Label>> infos = new AtomicReference<>( new HashSet<Label>() );
我如何能实现相同的功能环路与流现在在做什么?
你可以不用AtomicReference
:
BinaryOperator<Label> logDuplicate = (label1, label2) -> {
// Log label2 as duplicate
compileResult.add(new CompileResult(Severity.FATAL, MessageFormat.format("Duplicate label found! \n Type: '{0}' \n Language: '{1}'", label2.getType(), label2.getLanguage())));
return label1;
};
Set<Label> infos = infoRepo.getList()
.stream()
.filter(Label.class::isInstance)
.map(Label.class::cast)
.collect(toMap(identity(), identity(), logDuplicate, HashMap::new))
.keySet();
更新:
import static java.util.stream.Collectors.toMap;
import static java.util.function.Function.identity;