[英]Java print items in tree map list
I currently have a TreeMap of the form <String, List<List<String>>
我目前有一个
<String, List<List<String>>
形式的 TreeMap
I'm trying to write my tree map to an output file where I get the inner values of my string[] all separated by a colon.我正在尝试将我的树图写入一个输出文件,在那里我得到 string[] 的内部值,所有值都用冒号分隔。
Do I need a second for loop to loop through each inner list and format it using a .join(":", elements)
?我是否需要第二个 for 循环来遍历每个内部列表并使用
.join(":", elements)
对其进行格式化?
Or is there a more concise way to keep it all in a single for loop statement?或者是否有更简洁的方法将所有内容保存在单个 for 循环语句中?
I've tried a few things and my current code is:我尝试了几件事,我当前的代码是:
new File(outFolder).mkdir();
File dir = new File(outFolder);
//get the file we're writing to
File outFile = new File(dir, "javaoutput.txt");
//create a writer
try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), "utf-8"))) {
for (Map.Entry<String, String[]> entry : allResults.entrySet()) {
writer.write(entry.getKey() + ", "+ Arrays.toString(entry.getValue()).replace("null", "").toString());
writer.newLine();
}
Current output:电流输出:
ANY, [[469, 470], [206, 1013, 1014], [2607, 2608]]
任何, [[469, 470], [206, 1013, 1014], [2607, 2608]]
Desired output:期望的输出:
ANY, 469:470, 206:1013:1014, 2607:2608
任何、469:470、206:1013:1014、2607:2608
Any suggestions would be greatly appreciated.任何建议将不胜感激。
String.join(":", arr)
can be used to take the String array and return a colon-separated String. String.join(":", arr)
可用于获取 String 数组并返回以冒号分隔的 String。 This can then be used with Streams with a Collector to join these strings with a comma-separator, so :然后可以将其与带有收集器的 Streams 一起使用,以使用逗号分隔符连接这些字符串,因此:
TreeMap<String, String[]> allResults = new TreeMap<>();
allResults.put("a", new String[]{"469", "470"});
allResults.put("b", new String[]{"206", "1013", "1014"});
allResults.put("c", new String[]{"2607", "2608"});
String result = allResults.entrySet().stream()
.map(e -> String.join(":", e.getValue()))
.collect(Collectors.joining(", "));
System.out.println(result);
produces :产生:
469:470, 206:1013:1014, 2607:2608
With a List<List<String>>
, you need a stream within a stream, so :使用
List<List<String>>
,您需要流中的流,因此:
TreeMap<String, List<List<String>>> allResults = new TreeMap<>();
allResults.put("a", Arrays.asList(Arrays.asList("469", "470"), Arrays.asList("206", "1013", "1014"), Arrays.asList("2607", "2608")));
allResults.put("b", Arrays.asList(Arrays.asList("169", "470")));
allResults.put("c", Arrays.asList(Arrays.asList("269", "470")));
String result = allResults.entrySet().stream()
.map(i -> i.getKey() + "," + i.getValue().stream().map(elements -> String.join(":", elements))
.collect(Collectors.joining(", "))
)
.collect(Collectors.joining("\n"));
System.out.println(result);
which produces :产生:
a,469:470, 206:1013:1014, 2607:2608
b,169:470
c,269:470
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.