技術メモ

神奈川在住のITエンジニアの備忘録。おもにプログラミングやネットワーク技術について、学んだことを自分の中で整理するためにゆるゆると書いています。ちゃんと検証できていない部分もあるのでご参考程度となりますが、誰かのお役に立てれば幸いです。

Javaで 2つの配列の共通部分を取得する。

競技プログラミングの問題を解いていて必要になったので、Javaで 2つの配列の共通部分を取得するメソッドを作成した。1つ目のメソッドは int 用で、2つ目は String 用。

    // 二つの数値の配列のうち、共通する項目を取り出す。
    int[] getCommonNumbers (int[] x, int[] y) {
        // どちらかが null の場合は、空の配列を返す。(呼び出し元で NullPointerException を起こさないため。)
        if (x == null || y == null) {
            return new int[0];
        }
        List<Integer> commons = new ArrayList();
        int count = 0;
        for (int elemX : x) {
            for (int elemY : y) {
                if (elemX == elemY) {
                    commons.add(elemX);
                    count++;
                }
            }
        }
        int[] result = new int[count];
        for (int i = 0; i < count; i++) {
            result[i] = commons.get(i);
        }
        return result;
    }

    // 二つの文字列の配列のうち、共通する項目を取り出す。
    String[] getCommonStrings (String[] x, String[] y) {
        // どちらかが null の場合は、空の配列を返す。(呼び出し元で NullPointerException を起こさないため。)
        if (x == null || y == null) {
            return new String[0];
        }
        List<String> commons = new ArrayList();
        int count = 0;
        for (String elemX : x) {
            for (String elemY : y) {
                if (elemX.equals(elemY)) {
                    commons.add(elemX);
                    count++;
                }
            }
        }
        String[] result = new String[count];
        for (int i = 0; i < count; i++) {
            result[i] = commons.get(i);
        }
        return result;
    }

Javaでは可変長の配列がないので、あまりカッコよくないが、、共通部分の取得結果を一旦 List に格納して、最後に List を配列に変換している。