is one char array Subset of another char array - Java Collection Framework

Java examples for Collection Framework:Array Sub Array

Description

is one char array Subset of another char array

Demo Code


//package com.java2s;
import java.util.ArrayList;

import java.util.List;

public class Main {
    public static void main(String[] argv) throws Exception {
        char[] charArr1 = new char[] { 'b', 'o', 'o', 'k', '2', 's', '.',
                'c', 'o', 'm', 'a', '1', };
        char[] charArr2 = new char[] { 'b', 'o', 'o', 'k', '2', 's', '.',
                'c', 'o', 'm', 'a', '1', };
        System.out.println(isSubset(charArr1, charArr2));
    }//from  w  w w .j av a 2s .  c  o m

    public static boolean isSubset(char[] charArr1, char[] charArr2) {
        if (charArr1.length > charArr2.length) {
            return false;
        }
        List<Character> charList1 = toList(charArr1);
        List<Character> charList2 = toList(charArr2);
        // cannot do containsAll as there can be duplicate characters
        for (Character charValue : charList1) {
            if (charList2.contains(charValue)) {
                charList2.remove(charValue);
            } else {
                return false;
            }
        }
        return true;
    }

    private static List<Character> toList(char[] charArr) {
        assert charArr != null;
        List<Character> charList = new ArrayList<Character>();
        for (char ch : charArr) {
            charList.add(ch);
        }
        return charList;
    }
}

Related Tutorials