static TreeMap<Integer, String> parseElementsBeforeOpenBracket(String inValue) {
StringTokenizer tokenizer = new StringTokenizer(inValue, "[]", true);
TreeMap<Integer, String> mapElements = new TreeMap<>();
int i = 0;
while (tokenizer.hasMoreElements()) {
String s = (String) tokenizer.nextElement();
mapElements.put(i, s);
i += s.length();
}
return mapElements;
}
Expecting: something like TreeMap<Integer, String> mapElements = xxx.stream()...Collectors.toMap()
I don't know how to use lambda, but, as the official doc says you can use
MathchandPatternunderjava.util.regexpackage instead ofStringTokenizer:I tested with
ozh22a]xyz4[4b3[3c]]abc5[5]abcdeand got the same result as your code{0=ozh22a, 6=], 7=xyz4, 11=[, 12=4b3 , 15=[, 16=3c, 18=], 19=], 20=abc5, 24=[, 25=5, 26=], 27=abcde}Maybe you can't think of
[^\\[\\]]+|\\[|\\]very quickly, but observing your code results can be divided into three parts:[or]->[^\\[\\]]+[->\\[]->\\]\\is an escapeIf you are not familiar with the methods of the
Matcherclass, please see Module java.base Package java.util.regex Class Matcher.If you use jdk9 and above, you can use the
Matcher.result()method, such asmatcher.results().collect(TreeMap::new, (map, matchResult) -> map.put(matchResult.start(), matchResult.group()), TreeMap::putAll);This can directly get a TreeMap result.
Please see Matcher.results().I didn't test it because I'm using JDK8.
I am not very good at English, I use Google Translate, which may affect reading, please forgive me. Hope to help you.