Java 如何读取文本文件并使用hashmap存储?

Java 如何读取文本文件并使用hashmap存储?,java,hashmap,Java,Hashmap,我有一个文本文件,3列中有整数,第一列中的每个数字都有多个条目,如上面的示例所示: 1 23 1 1 24 2 1 57 1 1 10 1 1 59 2 1 31 2 1 38 1 1 11 1 2 39 2 2 40 1 2 15 1 2 74 2 我可以用上面显示的代码读取文件的内容 public static void main(String[] args) { try (BufferedReader br = new BufferedReader(new FileReader

我有一个文本文件,3列中有整数,第一列中的每个数字都有多个条目,如上面的示例所示:

1 23 1
1 24 2
1 57 1
1 10 1
1 59 2
1 31 2
1 38 1
1 11 1
2 39 2
2 40 1
2 15 1
2 74 2
我可以用上面显示的代码读取文件的内容

public static void main(String[] args) {

    try (BufferedReader br = new BufferedReader(new FileReader("/home/user/Desktop/file.txt")))
        {
            String sCurrentLine;
            while ((sCurrentLine = br.readLine()) != null) {
                System.out.println(sCurrentLine);
            }
        } 
    catch (IOException e) {
                e.printStackTrace();
        } }
但我想使用hashmap将第一列中每个不同数字的所有条目连接在一行中,如下所示:

1 23 1 24 2 57 1 10 1 59 2 31 2 38 1
2 39 2 40 1 15 1 74 2
你有什么建议吗?
谢谢

HashMap是将键映射到特定值的对象。这是tobias_k建议的一个实现:

HashMap<int, String> map = new HashMap<int,String>();

public static void main(String[] args) {

    try (BufferedReader br = new BufferedReader(new FileReader("/home/user/Desktop/file.txt")))
        {
            String sCurrentLine;
            while ((sCurrentLine = br.readLine()) != null) {
                // ** NEW CODE **
                // get first int in current line
                int first = Integer.parseInt(sCurrentLine.substring(0, sCurrentLine.indexOf(" ")))
                // get rest of line
                String rest = sCurrentLine.substring(sCurrentLine.indexOf(" ")).trim();
                // get what is currently in for key value and append to it what you just got
                map.put(first, map.get(first) + rest);

                System.out.println(sCurrentLine);
            }
        } 
    catch (IOException e) {
                e.printStackTrace();
        } } 

免责声明可能不是100%有效的语法

以下是一些基本代码,可以帮助您入门。这将使用一个树形图对条目进行排序。请阅读下面的简介,了解原因,其中指定HashMap不保证条目的顺序。可以使用HashMap实现这一点,但我不建议使用它,因为您可能需要在某些地方执行额外的步骤

TreeMap<Integer, ArrayList<Integer[]>> rowMap = new TreeMap<Integer, ArrayList<Integer[]>>();

// when you have your new line

String[] cols = sCurrentLine.split(" ");

if (cols.length < 1) {
    // handle error if there is not a key column
}

try {
    int colKey = Integer.parseInt(cols[0]);

    Integer[] colValues = new Integer[cols.length - 1];

    for (int i = 1; i < cols.length; i++) {
        colValues[i - 1] = Integer.parseInt(cols[i]);
    }

    if (!rowMap.containsKey(colKey)) {

        // add a new entry for this column number
        rowMap.put(colKey, new ArrayList<Integer[]>());
    }

    rowMap.get(colKey).add(colValues);

} catch (NumberFormatException e) {
    // handle error if any columns don't have integers
}
这将输出以下内容:

// iterate by column 1 number in numerical order
for (Integer key : rowMap.keySet()) {

    // iterate by rows in this column in the order they were added
    for (Integer[] row : rowMap.get(key)) {
        String printout = key + ":";

        // iterate by columns in this row
        for (Integer col : row) {
            printout += " " + col;
        }

        System.out.println(printout);
    }
}
1: 23 1
1: 24 2
1: 57 1
1: 10 1
1: 59 2
1: 31 2
1: 38 1
1: 11 1
2: 39 2
2: 40 1
2: 15 1
2: 74 2
因此,您可以看到它根据第1列中的值对文档进行排序。您也可以按照OP中显示的格式打印它们,只需稍微更改循环,就可以将行添加到同一行

关于以这种方式使用TreeMap的一些注意事项:

  • 第1列中的数字可以是任意整数
  • 第1列中的数字可以是任意顺序
  • 除了第一行之外,这些行可以有任意数量的列
但是,当您使用映射列出它们时,它们将始终按第1列编号分组,并且它们将始终按数字顺序排列


如果您不关心保持行的排序,那么它可能会有点简化。在这种情况下,您可以生成一个
TreeMap
TreeMap
,甚至是一个
TreeMap
,如果您所做的只是将每一行串联起来。

下面的代码对我更有效,并显示了为每个行中的不同数字聚合的所有数字第一列。感谢大家发布解决方案。如果您对此有任何建议,请随时提出

public static void main(String[] args) {

    String sCurrentLine;
    TreeMap<Integer, ArrayList<Integer[]>> rowMap = new TreeMap<Integer, ArrayList<Integer[]>>();
    try (BufferedReader br = new BufferedReader(new FileReader("/home/user/Desktop/file.txt")))
        {
            while ((sCurrentLine = br.readLine()) != null) {

                String[] cols = sCurrentLine.split(" ");

                if (cols.length < 1) {
                }

                try {
                    int colKey = Integer.parseInt(cols[0]);

                    Integer[] colValues = new Integer[cols.length - 1];

                    for (int i = 1; i < cols.length; i++) {
                        colValues[i - 1] = Integer.parseInt(cols[i]);
                    }

                    if (!rowMap.containsKey(colKey)) {
                        rowMap.put(colKey, new ArrayList<Integer[]>());
                    }
                    rowMap.get(colKey).add(colValues);
                } catch (NumberFormatException e) {
                }
                for (Integer key : rowMap.keySet()) {
                    String row = key + ""; 
                    for (Integer[] rows : rowMap.get(key)) {
                        for (Integer col : rows) {
                            row += " " + col;
                        }
                    }
                    System.out.println(row);
                }
    }
    catch (IOException e) {
            e.printStackTrace();
    }
}
publicstaticvoidmain(字符串[]args){
弦电流线;
TreeMap rowMap=新建TreeMap();
try(BufferedReader br=new BufferedReader(new FileReader(“/home/user/Desktop/file.txt”))
{
而((sCurrentLine=br.readLine())!=null){
字符串[]cols=sCurrentLine.split(“”);
如果(列长度<1){
}
试一试{
int colKey=Integer.parseInt(cols[0]);
整数[]colValues=新整数[cols.length-1];
for(int i=1;i
为什么要使用hashmap执行此任务?它似乎不是正确的数据结构,特别是当您需要按文件中显示的两个输出行排序时。您可以使用hashmap存储{number->string},然后获取与当前行编号对应的字符串(如果没有,则创建一个新条目)并追加行(不带第一个数字)。到底是什么问题?@TedHopp一个朋友让我试试这个,但我很困惑。你能提供一些示例代码供建议吗?听起来HashMap不能做你想做的事情,因为HashMap键必须是唯一的。你不能有一个看起来像
1,23
的HashMap条目和另一个看起来像
1,24
的HashMap条目。其他ise我不确定我是否理解您的意图。我还相信@TedHopp所指的是HashMap不能保证其条目的顺序一致。@Radoidef我在想,在HashMap中,我可以有一些类似键:1值:23 1 24 2 57 1 10 1 59 2 31 2 38 1,键:2值:39 2 40 1 15 1 74 2代表的anksly,似乎工作正常,只需要一些调整。感谢您的回复。似乎我无法了解打印循环中的错误,说变量行已在方法中定义,但我看不到…在我的示例中,我在打印循环中仅声明了一次(
字符串行;
)。请确保分配变量行的第二个循环(看起来像
行=
)不是声明(
字符串行=
)。如果需要,您也可以同时声明和实例化行。这并不重要。我更改了示例以显示该行。@Radiodef您实际上是在声明
两次:一次作为
整数[]
和一次作为
String
。我想第一行
应该是
。我想已经完成了!我将发布一个回复,其中包含对我有用的代码,以供记录。谢谢大家的帮助!@tobias_k是的,你说得对!我会修复它。我在写作的中途修改了结构,我想我忘了更新一些p艺术:/
public static void main(String[] args) {

    String sCurrentLine;
    TreeMap<Integer, ArrayList<Integer[]>> rowMap = new TreeMap<Integer, ArrayList<Integer[]>>();
    try (BufferedReader br = new BufferedReader(new FileReader("/home/user/Desktop/file.txt")))
        {
            while ((sCurrentLine = br.readLine()) != null) {

                String[] cols = sCurrentLine.split(" ");

                if (cols.length < 1) {
                }

                try {
                    int colKey = Integer.parseInt(cols[0]);

                    Integer[] colValues = new Integer[cols.length - 1];

                    for (int i = 1; i < cols.length; i++) {
                        colValues[i - 1] = Integer.parseInt(cols[i]);
                    }

                    if (!rowMap.containsKey(colKey)) {
                        rowMap.put(colKey, new ArrayList<Integer[]>());
                    }
                    rowMap.get(colKey).add(colValues);
                } catch (NumberFormatException e) {
                }
                for (Integer key : rowMap.keySet()) {
                    String row = key + ""; 
                    for (Integer[] rows : rowMap.get(key)) {
                        for (Integer col : rows) {
                            row += " " + col;
                        }
                    }
                    System.out.println(row);
                }
    }
    catch (IOException e) {
            e.printStackTrace();
    }
}