java - 列为 Java 中 hashMap 的值

标签 java data-structures collections

文件:

Person1:AP
Person2:AP
Person3:KE
Person4:KE
Person5:UK
Person6:AP
Person7:UK
Person8:AP

我试过的是:

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;

public class TestNull {

    public static void main ( String args[]) throws IOException {

        BufferedReader br = new BufferedReader ( new FileReader("/home/username/Desktop/test"));
        String str;
        HashMap<String, String> h = new HashMap<String, String>();

        try {
            while ( (str = br.readLine()) != null)  {
                String[] s = str.split(":");
                h.put(s[1],s[0]);
            }
            System.out.println(h);
        }

        catch (FileNotFoundException E) {   
            System.out.println("File Not Found");
        }
        finally {   
            br.close();
        }
    }
}  

我可以通过 Perl 实现:

use strict;
use warnings;

open (FILE,"test");

my %hash=();
while (my $line = <FILE>)   {

    chomp $line;

    my ($name,$country) = split(":", $line);

    chomp ($name,$country);

    $hash{$country} .= "$name ";    
}

for my $keys (keys %hash)   {

    print "$keys: $hash{$keys}\n";

}

从数据文件中,我正在寻找这样的输出:

{AP = [person1, person 2, person6, person8], KE = [person3, person4], UK = [person5, person7]}

最佳答案

以下是你需要的-

Map<String, List<String>> h = new HashMap<String, List<String>>();

对于每一行——

String[] s = str.split(":"); //s[1] should be the key, s[0] is what should go into the list 
List<String> l = h.get(s[1]); //see if you already have a list for current key
if(l == null) { //if not create one and put it in the map
    l = new ArrayList<String>();
    h.put(s[1], l);
}
l.add(s[0]); //add s[0] into the list for current key 

关于java - 列为 Java 中 hashMap 的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16907594/

相关文章:

java - 如何在java中将当前时间添加到上一个日期?

java - 向 Apache TelnetClient 发送字节命令

java - 轮询 Pod 的就绪状态

c++ - 哪个数据结构在附加重复项时提供替换操作?

algorithm - 搜索文件中最常出现的模式

javascript - Meteor:插入时过滤属性不起作用

java - URLDecoder.decode(encodedString, "UTF-8") 替代方案

c - b->next->next 在链表中给出错误

Scala 增强集合

java - 集合上的 QueryDSL -> 字符串列表的任何()