Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I turn this into a stream expression? (Using AtomicReference)

I need to change the code below:

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 );
        }
    }
}

Into a stream. I know that one way to use Sets with streams is by implementing AtomicReferences, which would replace the first line of the method into this:

AtomicReference<Set<Label>> infos = new AtomicReference<>( new HashSet<Label>() );

How can I achieve the same functionality that the loop is doing now with a stream?

like image 718
Juan Pollacchi Avatar asked Mar 24 '26 16:03

Juan Pollacchi


1 Answers

You can do it without 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();

Update:

import static java.util.stream.Collectors.toMap;
import static java.util.function.Function.identity;
like image 159
ETO Avatar answered Mar 27 '26 11:03

ETO



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!