set Difference for char array - Java Collection Framework

Java examples for Collection Framework:Set

Description

set Difference for 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(java.util.Arrays.toString(setDifference(
                charArr1, charArr2)));/*from  www .  ja  va2 s  . c om*/
    }

    public static char[] setDifference(char[] charArr1, char[] charArr2) {
        List<Character> list1 = toList(charArr1);
        List<Character> list2 = toList(charArr2);
        for (Character charObj : list2) {
            list1.remove(charObj);
        }
        return toCharArray(list1);
    }

    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;
    }

    private static char[] toCharArray(List<Character> charList) {
        if (charList == null || charList.isEmpty()) {
            return new char[0];
        }

        char[] charArr = new char[charList.size()];
        for (int index = 0; index < charList.size(); index++) {
            charArr[index] = charList.get(index);
        }
        return charArr;
    }
}

Related Tutorials