Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

list as value of hashMap in Java

File:

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

What I have tried is:

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

I could achieve this by 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";
    
}

From the data file, I am looking for an out put like this:

{
  AP = [person1, person2, person6, person8],
  KE = [person3, person4],
  UK = [person5, person7]
}
like image 461
gthm Avatar asked May 11 '26 18:05

gthm


1 Answers

Following is what you need -

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

And for every line -

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 
like image 134
Bhesh Gurung Avatar answered May 13 '26 07:05

Bhesh Gurung



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!