Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/350.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 查找数组中一个数的最大发生次数_Java - Fatal编程技术网

Java 查找数组中一个数的最大发生次数

Java 查找数组中一个数的最大发生次数,java,Java,我有一个数组{2,22,33,20222},将输入作为2传递。我要查找2的最大数字出现次数 产出:222 因为222在给定数组中最多包含2个 有人能帮我编写上述要求的示例java程序吗。实现这一点的最简单(我认为)方法是将数据数组中的每个数字转换为字符串。然后,您可以在此字符串中计算输入号码的出现次数。最后,一个比较器可以找到出现次数最多的比较器: /** * Will return the first number of the data array if none of the numbe

我有一个数组{2,22,33,20222},将输入作为2传递。我要查找2的最大数字出现次数

产出:222 因为222在给定数组中最多包含2个

有人能帮我编写上述要求的示例java程序吗。

实现这一点的最简单(我认为)方法是将数据数组中的每个数字转换为
字符串。然后,您可以在此
字符串中计算输入号码的出现次数。最后,一个比较器可以找到出现次数最多的比较器:

/**
 * 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());
}

大家好,欢迎来到StackOverflow!您似乎认为StackOverflow是一个发布问题并获得一些代码作为回报的站点。事实并非如此。您的问题很可能很快就会被关闭甚至删除。为了防止将来发生这种情况,请和。特别地,
@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));
}