1

With the following code I was able to get all the necessary information out of a form, this information is;

n = 5
p = 0.5
lambda = 0.3
d = 1
n = 8
p = 0.1
d = 1
p = 0.3

I put all this information in a HashMap, but what I actually need would be 6 hashmaps; like this

Hashmap 1
n = 5
p = 0.5
Hashmap 2
lambda = 0.3
Hashmap 3
d = 1
Hashmap 4
n = 8
p = 0.1
Hashmap 5
d = 1
Hashmap 6
p = 0.3

In other words, always when I get an n as keyword, the next keyword and value should also be stored in this Hashmap, this next keyword will always be an p.

I know it is not really possible to split a Hashmap, but I can't find any other way

Thanks a lot

public static void main(String[] args ) throws FileNotFoundException, IOException        
{
     File filename = new File("H:\\NetBeansProjects\\thesis2.0\\src\\thesis2\\pkg0\\txt-files\\formulier.txt");

     try (BufferedReader in = new BufferedReader(new FileReader(filename))) 
     {

        HashMap hm = new HashMap();

        Pattern p = Pattern.compile("\\s+(\\w+)\\s+([0-9.]+)\\s*");
        for (String line; (line = in.readLine()) != null; ) 
        {
            Matcher m = p.matcher(line);
            if (m.matches()) 
            {
                String keyword = m.group(1);
                String parameter = m.group(2);

                hm.put(m.group(1),m.group(2));

                System.out.println(m.group(1) + " = " + m.group(2));
            }
       }
    }  
}
Slava Vedenin
  • 58,326
  • 13
  • 40
  • 59
StudentX
  • 565
  • 1
  • 4
  • 7

1 Answers1

1

You can use a List<> to store the Map<>s, you basicly need to create a simple token based parser for the values that dispatches it to the next Map.

List<Map<String,String>> motherList = new ArrayList<>();
Map<String,String> workingChild = new HashMap<>();

.... 

String keyword = m.group(1);
String parameter = m.group(2);

workingChild.put(keyword,parameter);
if(!keyword.equals("n")) {
    motherList.add(workingChild);
    workingChild = new HashMap<>();
}

We basically have 1 motherlist containing al our child maps, for every input keyword and parameter, we put it in our current work map, and then we put it in the motherMap ONLY if the last token wasn't "n".

Ferrybig
  • 18,194
  • 6
  • 57
  • 79
  • thank you for your answer, I was wondering if this would work because in the list their is always added a map workingChild, will this not override the previous made Hashmap, also called workingChild ? – StudentX Feb 02 '16 at 14:27
  • @StudentX [Java is always pass by value](http://stackoverflow.com/a/40499/1542723), so our resulting HashMap will be put in the list, and we can then reuse the reference `workingChild` without affecting the Map in the List. – Ferrybig Feb 02 '16 at 14:29