Note that there are some explanatory texts on larger screens.

plurals
  1. POGet random value from HashMap
    text
    copied!<p>I want to get random value of HashMap, but only from one key.</p> <p>This is how i build my HashMap. Every Key has multiple values.</p> <pre><code>ArrayList&lt;HashMap&lt;String, String&gt;&gt; items = new ArrayList&lt;HashMap&lt;String, String&gt;&gt;(); for (.....) { // creating new HashMap HashMap&lt;String, String&gt; map = new HashMap&lt;String, String&gt;(); Element e = (Element) nl.item(i); map.put(KEY_1, parser.getValue(e, KEY_1)); map.put(KEY_2, parser.getValue(e, KEY_2)); // adding HashList to ArrayList items.add(map); } </code></pre> <p>So key "KEY_1" has multiple values so do "KEY_2". Now i want to get random value using key "KEY_1". How to do that ?</p> <p>EDIT: I think i know where is problem, although dont know yet how to fix that. Problem is defining size(); I need somehow get size not from all HashMap items like "items.size();" but something more similar to "items.KEY_1.size();"</p> <p>With this code getting NullPointerException</p> <pre><code>int index = random.nextInt(items.size()); HashMap&lt;String, String&gt; randomitem = new HashMap&lt;String, String&gt;(); randomitem = items.get(index); System.out.println(randomitem.get(KEY_1)); </code></pre> <p>With this code im able to get value not random:</p> <pre><code>int index = 2; HashMap&lt;String, String&gt; randomitem = new HashMap&lt;String, String&gt;(); randomitem = items.get(index); System.out.println(randomitem.get(KEY_1)); </code></pre> <p><strong>EDIT:</strong> With this code i can get random values but i get values from all keys. How to get values only from one key ?</p> <pre><code>Random rand = new Random(); indexx = rand.nextInt(items.size()); System.out.println(items.get(indexx)); </code></pre> <p><strong>Solved</strong> With this code i can get random value from certain key.</p> <pre><code>Random rand = new Random(); indexx = rand.nextInt(items.size()); HashMap&lt;String, String&gt; randomitems = items.get(indexx); System.out.println(randomitems.get(KEY_1)); </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload