实现算法的最快方法是使用Java计算每个字符串在字符串数组中出现的次数

时间:2016-04-22 12:02:55

标签: java arrays algorithm

想知道实现算法的最快方法是使用Java计算每个字符串在字符串数组中出现的次数吗?

这就是我所尝试过的,它有效,但我担心这可能是“作弊”,因为它偏离了这个问题:

{
    String[] stringArray = {"Random", "Words", "Here","Random", "Words", "Here","Random", "Words", "Here","Random", "Words", "Here"};

    List asList = Arrays.asList(stringArray);
    Set<String> mySet = new HashSet<>(asList);

    mySet.stream().forEach((s) -> {
        System.out.println(s + " " +Collections.frequency(asList,s));
    });
}

3 个答案:

答案 0 :(得分:3)

最简单的方法是使用Map#merge()

Map<String, Integer> m = new HashMap<>();
for (String s : array)
    m.merge(s, 1, Integer::sum);

之后,m将字符串作为键和出现值保存:

m.forEach((k, v) -> System.out.format("%s occured %s time(s)\n", k, v));

答案 1 :(得分:1)

在溪流中使用收藏家:

Arrays.stream(list).collect(Collectors.groupingBy(e -> e, Collectors.counting()))

所以,如果你有这样的事情:

        String[] list = new String[4];
        list[0] = "something";
        list[1] = "gfddfgdfg";
        list[2] = "something";
        list[3] = "somet444hing";
        System.out.println(Arrays.stream(list).collect(Collectors.groupingBy(e -> e, Collectors.counting())));

输出将是:

{gfddfgdfg=1, something=2, somet444hing=1}

答案 2 :(得分:1)

我会使用groupingBy返回计数图。

Map<String, Long> counts = Stream.of(array)
                           .collect(Collectors.groupingBy(w -> w, Collectors.counting()));

也可以打印这些

Stream.of(array)
      .collect(Collectors.groupingBy(w -> w, Collectors.counting()))
      .forEach((k, v) -> System.out.println(k + " occurred " + v " times));