0

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

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

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

john Asked question May 13, 2021