LoginSignup
3
4

More than 5 years have passed since last update.

【Java】Mapの比較

Last updated at Posted at 2016-12-15

Mapの比較方法

・やりたいこと
リストAとリストBの比較を行い、どちらにもあるものとリストAにあるものだけ抽出したい
更新のときと新規のときで処理を変えたい

※2016/12/16:asahina_devさんの指摘を受けて修正しました。

qiita.rb
/* package whatever; // don't place package name! */

import java.util.*;
import java.lang.*;
import java.io.*;

/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
    public static void main (String[] args) throws java.lang.Exception
    {
        // MAP-A
        Map<String, String> listA = new HashMap<String, String>();
        listA.put("fruits","apple");
        listA.put("animal","cat");
        listA.put("sports","soccer");
        listA.put("drink","water");
        // MAP-B
        Map<String, String> listB = new HashMap<String, String>();
        listB.put("sports","soccer");
        listB.put("fruits","apple");
        listB.put("color","red");

        //Set<Map.Entry<K,V>>でまわしてリストBにもあれば更新、なければ新規
        for(Map.Entry<String,String> entry : listA.entrySet()){
            String key = entry.getKey();
            String val = entry.getValue();
            if(listB.get(key) != null){
                entry.setValue(val + "Koshin");
            } else {
                entry.setValue(val + "Shinki");
            }
        }   
        System.out.println(listA);
    }
}

実際にはもっと複雑だったけど、簡易化するとこんな感じになった。
最初はリストCを用意しておいて共通した要素をリストCに放り込んで、リストA,Bからはその要素を削除していき、最後にリストAに要素が残っていれば新規としていれるって形にしたんだけど、iteratorで回してる時にその要素に変更を加えるとだめらしく、エラーが発生したので変更した。このほうがすっきりしてていいね。

3
4
4

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
3
4