Skip to content

Instantly share code, notes, and snippets.

@StFS
Created August 2, 2018 16:54
Show Gist options
  • Save StFS/65cd3524590be75bd356662f3de9bee8 to your computer and use it in GitHub Desktop.
Save StFS/65cd3524590be75bd356662f3de9bee8 to your computer and use it in GitHub Desktop.
List<String> toollist = // a list of tool ids
Set<String, String> mapToolId = // a map convert ids to fully qualified names
Set<String> fqToolList = toollist.stream()
.peek( n -> { if (!mapToolId.containsKey(n.trim())) logger.warn("Ignoring unexpected tool id value '{}'", n); })
.filter( n -> mapToolId.containsKey(n.trim()) )
.map( n -> mapToolId.get(n.trim())) // map shorthand tool names to fully qualified tool names
.collect( Collectors.toCollection(HashSet::new) ); // make sure we have a mutable set
@StFS
Copy link
Author

StFS commented Aug 2, 2018

önnur leið er svona:

Set<String> fqToolList = toollist.stream()
        .filter( n -> { if (mapToolId.containsKey(n.trim())) { return true; } else { logger.warn("Ignoring unexpected tool id value '{}'", n); return false; } } )
        .map( n -> mapToolId.get(n.trim())) // map shorthand tool names to fully qualified tool names
        .collect( Collectors.toCollection(HashSet::new) ); // make sure we have a mutable set

Kosturinn við þetta er að conditionið er ekki tvítekið... en gallinn er að þetta er ljótt og gerir filterinn mun ólæsilegri

@iamgoddog
Copy link

Hvað með þetta? Jújú, það er heilt nýtt fall hérna, en þú getur fært það einhvert annað í filtera-safn eða hvað sem þú myndir vilja gera. Gerir .filter() aðeins betra

List<String> toollist = new ArrayList<>();
Map<String, String> mapToolId = new HashMap<>();

Set<String> fqToolList = toollist.stream()
            .filter( contains( mapToolId ) )
            .map( n -> mapToolId.get( n.trim() ) ) // map shorthand tool names to fully qualified tool names
            .collect( Collectors.toCollection( HashSet::new ) ); // make sure we have a mutable set  

public Predicate<String> contains( final Map<String, String> map ) {
        return n -> {
            if( map.containsKey( n.trim() ) ) {
                return true;
            }
            else {
                logger.warn( "Ignoring unexpected tool id value '{}'", n );
                return false;
            }
        };
    }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment