Skip to content

Instantly share code, notes, and snippets.

@masanobuimai
Created January 26, 2017 02:41
Show Gist options
  • Save masanobuimai/54da8a86e3bd65b490de73e1c3c22407 to your computer and use it in GitHub Desktop.
Save masanobuimai/54da8a86e3bd65b490de73e1c3c22407 to your computer and use it in GitHub Desktop.
Map<String, Function<String, String>> switchCase = new HashMap<>();
switchCase.put("A", String::toLowerCase);
switchCase.put("a", String::toUpperCase);
Stream.of("A", "a", "aaa", "bbb")
.map(str -> Optional.ofNullable(switchCase.get(str))
.map(f -> f.apply(str))
.orElse(str))
.forEach(System.out::println)
@itohro
Copy link

itohro commented Jan 26, 2017

Eclipse CollectionsCaseFunctionを使うとこんな感じにスマートにいけますがどうでしょう。実際のコンテナはStreamでもEclipse Collectionsでもどちらでもいけます。(追記:toUpperCase()の箇所を間違えてたので直しました)

CaseFunction<String, String> switchCase = new CaseFunction<>();
switchCase.setDefault(s -> s);
switchCase.addCase("A"::equals, String::toLowerCase);
switchCase.addCase("a"::equals, String::toUpperCase);

Stream.of("A", "a", "aaa", "bbb")
        .map(switchCase)
        .forEach(System.out::println);

Lists.immutable.of("A", "a", "aaa", "bbb")
        .collect(switchCase)
        .each(System.out::println);

@masanobuimai
Copy link
Author

hum...
.map(str -> switchCase.getOrDefault(str, k -> str).apply(str))
.forEach(System.out::println)

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