-2

Here is My hashmap:

            if (m1.get(image.getRGB(x, y)) == null) {
            m1.put(image.getRGB(x, y), 1);

        } else {
            int newValue = Integer.valueOf(String.valueOf(m1.get(image.getRGB(x, y))));
            newValue++;
            m1.put(image.getRGB(x, y), newValue);

        }

then I print it like this:

for (Object key : m1.keySet()) {
        Color temp = new Color((int) key);
        int r = temp.getRed();
        int g = temp.getGreen();
        int b = temp.getBlue();
        System.out.println("r: " + r + " G: " + g + " B: " + b+ "\t\tValue: " + m1.get(key));

    }

How can I select the second value (second max in hashmap) of my hashmap save its value in another variable?

Wooopsa
  • 320
  • 1
  • 6
  • 22

2 Answers2

-1

If you can change, then change the implementation type to TreeMap. While iterating on them, they will display the data in sorted order.

You just need to define a comparator where you will define the meaning of higher and lower.

While creating treemap instance, pass this comparator

SacJn
  • 777
  • 1
  • 6
  • 16
  • I dont care for the type. I just want to save an image.rgb and its value in that image. which type is better and it let me to select the n-th value that i want? – Wooopsa Aug 26 '15 at 09:01
  • You dint mention earlier that you wanted the second highest. – SacJn Aug 26 '15 at 09:03
  • @Hamid `Map< TYPE 1, TYPE2 > map = new TreeMap < TYPE1, TYPE2 > (new Comparator () )`. You just need to declare one comparator for it – SacJn Aug 26 '15 at 09:12
-1

You can create a list with the values:

List<Integer> valuesList = new ArrayList<Integer>(m1.values());

Then sort it:

Collections.sort(valuesList, Collections.reverseOrder());

and finally get the second item:

int secondMax = valuesList.get(1);
Maroun
  • 94,125
  • 30
  • 188
  • 241
  • I want to keep the image.rgb AND its value. Is this gonna help? – Wooopsa Aug 26 '15 at 09:02
  • @Hamid No. You cannot get a key given a value. I suggest you to iterate on the hashmap, and compare the values while iterating on the keys. – Maroun Aug 26 '15 at 09:04
  • @MarounMaroun This solution will still not provide the key for which this value is being returned. So don't you think using treemap would be a better approach ? – SacJn Aug 26 '15 at 09:21
  • @SacJn It could be used of course. But I think iterating over the existing Hash Map should solve this as well.. – Maroun Aug 26 '15 at 11:33