LoginSignup
0
0

More than 3 years have passed since last update.

HashMap の値を取り出し,value の値でソートした結果をリストで返す

Last updated at Posted at 2020-06-04

javaでMap(HashMap)をvalueを使ってソートする際のやり方をまとめておきます.
ここでは,B_arrayを使ってA_arrayの値も同時にソートしたい状況を考えています.
HashMapのentry型を持つリストをソートする形なので,TreeMapなど,他のMapでも使えます.

コード
Solution.java
import java.util.*;

class Solution {
    public static void main(String[] args) {
        int[] A_array = {1,6,3,10,5};
        int[] B_array = {8,21,13,4,5};
        tryComperator(A_array, B_array);
    }
    public static void tryComperator(int[] a, int[] b){
        Map<Integer, Integer> map = new HashMap<Integer, Integer>();
        //配列の要素をhashmapに格納.
        for (int i = 0; i < a.length; i++){
            map.put(a[i], b[i]);
        }
        //Hashmapの各要素をリストに格納.
        List<Map.Entry> mapValuesList = new ArrayList<Map.Entry>(map.entrySet());
        //mapValuesList を出力してみる.(10=4 のような形で出力されるらしい.)
        for (Map.Entry v: mapValuesList){
            System.out.println("map>> "+v+",key>> "+v.getKey()+"value>> "+v.getValue());
        }
        //Comparatorクラスをインスタンス化
        Comparator<Map.Entry> comparator = new Comparator<Map.Entry>() {
            public int compare(Map.Entry entry1, Map.Entry entry2) {
                return ((Integer) entry1.getValue()).compareTo((Integer) entry2.getValue());
            }
        };
        //comparator を使ってソートする.
        Collections.sort(mapValuesList, comparator);
        //確認のための出力
        for (Map.Entry s : mapValuesList) {
            System.out.println(s);
        }
    }
}
出力
map>> 1=8,key>> 1value>> 8
map>> 3=13,key>> 3value>> 13
map>> 5=5,key>> 5value>> 5
map>> 6=21,key>> 6value>> 21
map>> 10=4,key>> 10value>> 4
10=4
5=5
1=8
3=13
6=21

valueの昇順に出力されました.

参考: http://kevin3sei.blog95.fc2.com/blog-entry-159.html

0
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0