如何从 Multimap 的字符串表示中删除第一个和最后一个字符?

How do you remove the first and the last characters from a Multimap's String representation?

我正在尝试将 Multimap.get() 的结果输出到文件中。但是我得到 [] 字符分别作为第一个和最后一个字符出现。

我尝试使用这个程序,但它没有在整数之间打印任何分隔符。我该如何解决这个问题?

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");
    }
}

您可以将 newSortedMap.get(key).toString() 分配给一个变量,比方说 stringList。现在调用 writer.println(stringList.substring(1,stringList.length()-1));

了解当您将列表传递给 writer.println 方法时,它将调用对象的 toString() 方法并写入输出。 list.toString() 方法 returns 一个所有值由 , 分隔的字符串,并在字符串的开头和结尾添加 []

只需使用 substring.

修改 String 本身

substring(int, int)

Returns a new string that is a substring of this string. The substring begins at the specified beginIndex and extends to the character at index endIndex - 1. Thus the length of the substring is endIndex-beginIndex.

因此,将 Map 转换为 String。然后,1String表示的第二个字符,其余使用mapString.length() - 1

这是一些工作代码:

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