Created
August 24, 2021 07:09
-
-
Save XGFan/ccf4c0aeb3d9dc6e32ce4ccf6cdaf411 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Flat2Nest { | |
public static void main(String[] args) { | |
String testProp = "java.class.version = 60.0\n" + | |
"java.home = /usr/lib/jvm/java-16-openjdk\n" + | |
"java.runtime.name = OpenJDK Runtime Environment\n" + | |
"java.runtime.version = 16.0.2+7\n" + | |
"java.specification.name = Java Platform API Specification\n" + | |
"java.specification.vendor = Oracle Corporation\n" + | |
"java.specification.version = 16\n" + | |
"java.vendor = N/A\n" + | |
"java.vendor.url = https://openjdk.java.net/\n" + | |
"java.vendor.url.bug = https://bugreport.java.com/bugreport/\n" + | |
"java.version = 16.0.2\n" + | |
"java.version.date = 2021-07-20\n" + | |
"java.vm.name = OpenJDK 64-Bit Server VM\n" + | |
"java.vm.specification.name = Java Virtual Machine Specification\n" + | |
"java.vm.specification.vendor = Oracle Corporation\n" + | |
"java.vm.specification.version = 16\n" + | |
"java.vm.vendor = Oracle Corporation\n" + | |
"java.vm.version = 16.0.2+7\n" + | |
"sun.arch.data.model = 64"; | |
Map<String, Object> initMap = Arrays.stream(testProp.split("\n")) | |
.map(it -> { | |
int i = it.indexOf("="); | |
return new AbstractMap.SimpleEntry<>( | |
it.substring(0, i).trim(), | |
it.substring(i + 1).trim()); | |
}) | |
.collect(Collectors.toMap( | |
AbstractMap.SimpleEntry::getKey, | |
AbstractMap.SimpleEntry::getValue) | |
); | |
System.out.println(initMap); | |
Map<String, Object> finalMap = nestMap(initMap); | |
System.out.println(finalMap); | |
} | |
public static Map<String, Object> nestMap(Map<String, Object> map) { | |
Set<String> keys = new HashSet<>(); | |
keys.addAll(map.keySet()); | |
int size = 1; | |
String flag = null; | |
/*第一次遍历,取出最深层次的key*/ | |
for (String s : keys) { | |
/*两次转义*/ | |
String[] temp = s.split("\\."); | |
int dotNum = temp.length; | |
if (size < dotNum) { | |
size = dotNum; | |
flag = s.substring(0, s.lastIndexOf(".")); | |
} | |
} | |
/*递归跳出*/ | |
if (flag == null) { | |
return map; | |
} | |
Map<String, Object> subMap = new HashMap<>(); | |
/*第二次遍历,将最深层次变为map*/ | |
for (String v : keys) { | |
if (v.startsWith(flag)) { | |
if (v.length() > flag.length()) { | |
subMap.put(v.substring(flag.length() + 1), map.get(v)); | |
} else { | |
subMap.put(flag, map.get(v)); | |
} | |
map.remove(v); | |
} | |
} | |
/*将最深层次map放入*/ | |
map.put(flag, subMap); | |
/*递归*/ | |
return nestMap(map); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment