Java。在数组列表中查找字符串长度最大的字符串长度

时间:2020-01-10 19:25:47

标签: java arrays spring sorting arraylist

例如,说我分割后有以下数组。

[你好,世界,什么,好的,它是,日期,是,2020年1月10日]

10个字符-2020年1月10日(我知道这是一个日期字段,在这种情况下,它假装为字符串)

5个字符-世界,您好

4个字符-什么,还好,日期

3个字符-天,

2个字符-是,是

1个字符-a

因此,在这种情况下,我希望获得4个字符和2个字符,因为它们在列表数组中都具有最大的长度。

我们将不胜感激。谢谢!

1 个答案:

答案 0 :(得分:0)

您可以利用Java流库的groupingBy收集器

String[] arr = new String[]{
        "Hello",
        "world",
        "what",
        "a",
        "fine",
        "day",
        "it",
        "is",
        "the",
        "date",
        "is",
        "01/10/2020"
};

List<Integer> maxRepeatingSizes =
    Arrays.stream(arr)
            .collect(Collectors.groupingBy(
                String::length,
                Collectors.counting()
            )).entrySet()
            .stream()
            .collect(
                    Collectors.groupingBy(
                            Map.Entry::getValue,
                            Collectors.mapping(
                                Map.Entry::getKey,
                                Collectors.toList()
                            )
                    )
            ).entrySet()
            .stream()
            .max(
                    Map.Entry.comparingByKey()
            ).get()
            .getValue();

首先,使用字符串的长度作为键将数组分组,并将其计数为值。 接下来,将长度和计数的映射图反转以获得该计数的计数和长度列表。 然后,通过根据关键字对Map进行排序,以获取最大重复值。