How to remove first and last characters from Multimap String view?

I am trying to output the result of a Multimap.get()to a file. However, I get the characters [both ]as the first and last characters, respectively.

I tried to use this program, but it does not print separators between integers. How can I solve this problem?

package main;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;

import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Maps;
import com.google.common.collect.Multimap;

public class App {

public static void main(String[] args) {

    File file = new File("test.txt");
    ArrayList<String> list = new ArrayList<String>();
    Multimap<Integer, String> newSortedMap = ArrayListMultimap.create();

    try {
        Scanner s = new Scanner(file);
        while (s.hasNext()) {
            list.add(s.next());
        }
        s.close();
    } catch (FileNotFoundException e) {
        System.out.println("File cannot be found in root folder");
        ;
    }

    for (String word : list) {
        int key = findKey.convertKey(word);
        newSortedMap.put(key, word);
    }

    // Overwrites old output.txt
    try {
        PrintWriter writer = new PrintWriter("output.txt", "UTF-8");
        for (Integer key: newSortedMap.keySet()) {
            writer.println(newSortedMap.get(key));
        }
        writer.close(); 
    } catch (FileNotFoundException e) {
        System.out.println("FileNotFoundException e should not occur");
    } catch (UnsupportedEncodingException e) {
        System.out.println("UnsupportedEncodingException has occured");
    }
}
+4
source share
2 answers

You can assign to a newSortedMap.get(key).toString()variable, say stringList. Now callwriter.println(stringList.substring(1,stringList.length()-1));

, writer.println toString() . list.toString() , , [ ] .

+4

String, substring.

substring(int, int)

, . beginIndex endIndex - 1. , endIndex-beginIndex.

, Map String. 1 String mapString.length() - 1 .

:

PrintWriter writer = new PrintWriter("output.txt", "UTF-8");
String mapString = newSortedMap.toString();
writer.println(mapString.substring(1, mapString.length() - 1);
+2
source

All Articles