简体   繁体   中英

Is this the best performace way to use Java Stream api

I need to create a new list of strings from this array of strings:

    String[] groups = {
            "A_group1,AAAAA",
            "A_group2",
            "A_group3",
            "B_group4",
            "B_group5",
            "B_group6,BBBBBBB",
            "C_group7",
            "C_group8",
            "C_group9,CCCCC",
    };
    

where i have to keep strings that start with these prefixes:

    Map<String, String> mapping = new HashMap<>();
    mapping.put( "prefix1", "A_" );
    mapping.put( "prefix2", "B_" );

I would like to use Java Streams, but I'm a novice with these apis, so I wrote this code:

    mapping.values().forEach( prefix ->
            roles.addAll( stream( groups ).parallel().filter(
                    group -> group.startsWith( prefix )
            ).map(
                    group -> group.split( "," )[0].substring( prefix.length() )
            ).collect( toList() ) )
    );
    

The result is:

    [group4, group5, group6, group1, group2, group3]        

It is correct. But I would like to know if there is a code with better performace

The logic is inefficient, and it has nothing to do with the use of streams.

Your outer loop should be on "groups", and then check against the set of values of mapping, which is O(1) complexity. Something like:

Set<String> filter = new HashSet<>(mapping.values());
stream( groups ).filter(g -> filter.contains(g.split("_")[0] + "_")). ...

If you loop over the filter you end up looping over groups n-times, making the complexity O(n^2) instead of linear.

The rest looks fine to me: no big changes if you use stream API or plain old for loop. Just be aware that parallelizing the stream makes sense if you have a large number of groups; for a small number of groups the overhead of managing a parallelization could make the execution actually slower

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM