文件:
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/