Q:

Find max occurances of anumber in an array

I've an array {2,22,33,20,222}, passing input as 2. I want find max occurrences of a number for 2.
Output: 222
because 222 contains maximum 2's in given array.
Can some one help me to write sample java program of above requirement.

A:

The easiest (I think) way to achieve that, is to convert each number of your data array to a String. Then you can count the occurrences of your input number in this String. Finally a comparator to find the one with the most occurrences will do the job:
/**
 * Will return the first number of the data array if none of the numbers contain the input number.
 */
public static int findNumberInArrayWithTheMostOccurrences(Integer[] data, int number) {
    //@formatter:off
    Pattern pattern = Pattern.compile(String.valueOf(number));
    Optional<String> result = Arrays.asList(data).stream()
            .map(String::valueOf) //Convert each number to a String
            .max((stringNum1, stringNum2) -> {//Comparing 2 strings
                Matcher m = pattern.matcher(stringNum1);
                int timesOfString1 = 0;
                while (m.find())
                    timesOfString1++;

                m = pattern.matcher(stringNum2);
                int timesOfString2 = 0;
                while (m.find())
                    timesOfString2++;
                return timesOfString1 - timesOfString2;
        });
    //@formatter:on
    return Integer.parseInt(result.get());
}

And a test unit (JUnit):
@Test
public void mainTest() {
    Integer[] data1 = { 2, 22, 33, 20, 222 };
    assertEquals(222, findNumberInArrayWithTheMostOccurrences(data1, 2));

    //Check if it returns the first element of the array when all numbers do not contain it
    assertEquals(2, findNumberInArrayWithTheMostOccurrences(data1, 215));

    Integer[] data2 = { 2, 2224, 3351, 20141414, 22214 };
    assertEquals(20141414, findNumberInArrayWithTheMostOccurrences(data2, 14));
}

