Skip to content

Instantly share code, notes, and snippets.

@asdf913
Created May 8, 2026 01:12
Show Gist options
  • Select an option

  • Save asdf913/362350d4a9afc818eee5113d916d4c78 to your computer and use it in GitHub Desktop.

Select an option

Save asdf913/362350d4a9afc818eee5113d916d4c78 to your computer and use it in GitHub Desktop.
Convert a String array into a java.util.Map
<dependencies>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.20.0</version>
</dependency>
</dependencies>
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Objects;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
public class StringArrayToMap {
public static void main(String[] args) {
//
final Iterable<String> iterable = Arrays.asList(null, "", " ", "=", "= ", " =", "==", "== ", " ==", "k=v");
//
if (iterable != null) {
//
iterable.forEach(x -> {
//
System.out.println(x + "->" + toMap(x));
//
});
//
} // if
//
}
private static Map<String, String> toMap(final String... ss) {
//
String s = null;
//
Map<String, String> map = null;
//
for (int i = 0; i < length(ss); i++) {
//
if (Objects.equals(s = ArrayUtils.get(ss, i), "=")) {
//
put(map = ObjectUtils.getIfNull(map, LinkedHashMap::new), "", "");
//
} else if (s != null && s.length() == 2 && s.charAt(0) == '=') {
//
put(map = ObjectUtils.getIfNull(map, LinkedHashMap::new), "", s.substring(1, s.length()));
//
} else if (s != null && s.length() == 2 && s.charAt(s.length() - 1) == '=') {
//
put(map = ObjectUtils.getIfNull(map, LinkedHashMap::new), s.substring(0, s.length() - 1), "");
//
} else if (s != null && s.indexOf('=') >= 0 && s.indexOf('=') == s.lastIndexOf('=')) {
//
put(map = ObjectUtils.getIfNull(map, LinkedHashMap::new), StringUtils.substringBefore(s, '='),
StringUtils.substringAfter(s, '='));
//
} else if (s != null && s.length() > 2 && s.indexOf('=') != s.lastIndexOf('=')) {
//
put(map = ObjectUtils.getIfNull(map, LinkedHashMap::new), StringUtils.substring(s, 0, s.indexOf('=')),
StringUtils.substring(s, s.indexOf('=') + 1));
//
} // if
//
} // for
//
return map;
//
}
private static <K, V> void put(final Map<K, V> instance, final K key, final V value) {
if (instance != null) {
instance.put(key, value);
}
}
private static int length(final Object[] instance) {
return instance != null ? instance.length : 0;
}
}
@asdf913
Copy link
Copy Markdown
Author

asdf913 commented May 8, 2026

Sample

null->null
->null
->null
=->{=}
= ->{= }
=->{ =}
==->{==}
== ->{== }
==->{ ==}
k=v->{k=v}

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