Shorten if statements with .contains in them

  • A+

I wanted to ask if there was a different way to go about the if-else boiler-plate situation I am having.

Every single if and else if has a string.contains comparison in them. I am using Java 8.

Is there a way to shorten this using something like x ? y : z? Or maybe a switch?

if (s.contains("ServerAdmin ")) {       data.setServerAdmin(s) // This happens everywhere } else if (s.contains("DocumentRoot")) {       data.setDocumentRoot(s) // This happens everywhere } else if (s.contains("ServerName")) {       data.setServerName(s) // This happens everywhere } else if (s.contains("ErrorLog")) {       data.setErrorLog(s) // This happens everywhere } else if (s.contains("CustomLog")) {       data.setCustomLog(s) // This happens everywhere } else if (s.contains("<Directory")) {       data.setDirectory(s) // This happens everywhere } 

Is there a better way to go about this?

~Thanks in advance for any assistance.

The Java 8iest solution I can think of is

Map<String, Consumer<String>> map = new LinkedHashMap<>(); map.put("ServerAdmin", data::setServerAdmin); map.put("DocumentRoot", data::setDocumentRoot); // ... map.entrySet().stream()     .filter(entry -> s.contains(entry.getKey()))     .findFirst()     .ifPresent(entry -> entry.getValue().accept(s)); 

Which uses a LinkedHashMap to keep the comparison order intact (in case that is relevant), then simply searches for the first contains and applies the corresponding function

I guess I would declare the map statically in practice and make the instance of your data class a parameter to save a map creation per execution. Would look like the following for example.

private static final Map<String, BiConsumer<Data, String>> MAP = new LinkedHashMap<>(); static {     MAP.put("ServerAdmin", Data::setServerAdmin);     MAP.put("DocumentRoot", Data::setDocumentRoot);     // ... } public void foo(Data data, String s) {     MAP.entrySet().stream()         .filter(entry -> s.contains(entry.getKey()))         .findFirst()         .ifPresent(entry -> entry.getValue().accept(data, s)); } 


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: