Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - HashMap Memory : optimization

I would like to know if there is a more efficient way of handling hash maps.

I have the following Map (primary) which is composed of its key and another Map as the value.

   final Map<String,Map<Boolean,String>> primaryMap = new HashMap<>();
     Map<Boolean,String> secondaryMap = new HashMap<>();

For each key I assign 2 secondaryMaps and I inititalize the secondary map again.The sequence is similar to the one displayed below:

 secondaryMap = new HashMap<>();
       secondaryMap.put(true, "A");
       primaryMap.put("DOG", listedMap);

        secondaryMap.put(false, "B");
        primaryMap.put("DOG", listedMap);

 secondaryMap = new HashMap<>();

        secondaryMap.put(true, "C");
        primaryMap.put("CAT", listedMap);

        secondaryMap.put(false, "D");
        primaryMap.put("CAT", listedMap);

Could it be that there is a more efficient way to do this? Does secondaryMap.clear() have an impact in the memory before calling secondaryMap = new HashMap<>();

Many thanks in advance,

Kat

like image 473
Katherine99 Avatar asked Jun 21 '26 12:06

Katherine99


1 Answers

In so far as the inner Map can only have two keys, you could replace it by a custom class :

final Map<String,Map<Boolean,String>> primaryMap = new HashMap<>();

could be :

final Map<String, Foo> map = new HashMap<>();

and you could populate it such as :

 map.put("DOG", new Foo("A", "B"));

where theFoo constructor could be :

public Foo(String valueForTrue, Sting valueForFalse){
   this.valueForTrue = valueForTrue;
   this.valueForFalse = valueForFalse;
}

It will spare some memory (as much less objects will be required) but overall it will make your code much clearer.

Of course if you may add the String value only for the true of the false case you could favor factory over public constructor in Foo such as :

private Foo(){
}

public static Foo ofTrue(String valueForTrue){
   Foo foo = new Foo();
   foo.valueForTrue = valueForTrue;
   return foo;
}

public static Foo ofFalse(String valueForFalse){
   Foo foo = new Foo();
   foo.valueForFalse = valueForFalse;
   return foo;
}

public static Foo of(String valueForTrue, Sting valueForFalse){
   Foo foo = new Foo();
   foo.valueForTrue = valueForTrue;
   foo.valueForFalse = valueForFalse;
   return foo;
}
like image 56
davidxxx Avatar answered Jun 24 '26 01:06

davidxxx



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!