在ArrayList()中找到最常见的String

Esp*_*enG 10 java arrays list arraylist

有没有办法找到最常见StringArrayList

ArrayList<String> list = new ArrayList<>();
list.add("test");
list.add("test");
list.add("hello");
list.add("test");
Run Code Online (Sandbox Code Playgroud)

应该从这个列表中找到"test"这个词 ["test","test","hello","test"]

VH-*_*NZZ 16

不要重新发明轮子并使用类的frequency方法Collections:

public static int frequency(Collection<?> c, Object o)
Run Code Online (Sandbox Code Playgroud)

返回指定集合中等于指定对象的元素数.更正式地,返回集合中元素e的数量,使得(o == null?e == null:o.equals(e)).

如果你需要计算所有元素的出现次数,请巧妙地使用Map和循环:)或者使用frequency上面的方法将列表放在Set中,并在集合的每个元素上循环.HTH

编辑/ Java 8:如果你想要一个功能更强大的Java 8单线程解决方案与lambdas,请尝试:

Map<String, Long> occurrences = 
  list.stream().collect(Collectors.groupingBy(w -> w, Collectors.counting()));
Run Code Online (Sandbox Code Playgroud)


Luk*_*der 9

在统计学中,这称为"模式".vanilla Java 8解决方案如下所示:

Stream.of("test","test","hello","test")
      .collect(Collectors.groupingBy(s -> s, Collectors.counting()))
      .entrySet()
      .stream()
      .max(Comparator.comparing(Entry::getValue))
      .ifPresent(System.out::println);
Run Code Online (Sandbox Code Playgroud)

产量:

test=3
Run Code Online (Sandbox Code Playgroud)

jOOλ是一个支持mode()流的库.以下程序:

System.out.println(
    Seq.of("test","test","hello","test")
       .mode()
);
Run Code Online (Sandbox Code Playgroud)

产量:

Optional[test]
Run Code Online (Sandbox Code Playgroud)

(免责声明:我为jOOλ背后的公司工作)


Cha*_*ngh 7

根据问题,具体来说只是为了得到单词,而不是次数(即键的值)。

String mostRepeatedWord 
    = list.stream()
          .collect(Collectors.groupingBy(w -> w, Collectors.counting()))
          .entrySet()
          .stream()
          .max(Comparator.comparing(Entry::getValue))
          .get()
          .getKey();
Run Code Online (Sandbox Code Playgroud)


Mar*_*oun 5

你可以做一个HashMap<String,Integer>.如果字符串已经出现在地图中,则将其增加1,否则将其添加到地图中.

例如:

put("someValue", 1);
Run Code Online (Sandbox Code Playgroud)

然后,再次假设它是"someValue",你可以这样做:

put("someValue", get("someValue") + 1);
Run Code Online (Sandbox Code Playgroud)

由于"someValue" 的为1,现在当你把它放入时,键将为2.

之后,您可以轻松浏览地图并提取具有最高价值密钥.

我没有写完整的解决方案,尝试构建一个,如果你有问题在另一个问题中发布它.最佳做法是自学.