peakstatus
peakstatus

Reputation: 441

Java print items in tree map list

I currently have a TreeMap of the form <String, List<List<String>>

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.

Do I need a second for loop to loop through each inner list and format it using a .join(":", elements)?

Or is there a more concise way to keep it all in a single for loop statement?

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]]

Desired output:

ANY, 469:470, 206:1013:1014, 2607:2608

Any suggestions would be greatly appreciated.

Upvotes: 0

Views: 532

Answers (1)

racraman
racraman

Reputation: 5034

String.join(":", arr) can be used to take the String array and return a colon-separated String. This can then be used with Streams with a Collector to join these strings with a comma-separator, so :

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 :

    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

Upvotes: 2

Related Questions