简体   繁体   中英

the quickest way to Implement an algorithm to count how many times each string is present in an array of strings using Java

Just wondering what the quickest way to Implement an algorithm to count how many times each string is present in an array of strings using Java would be?

this is what i have tried and it works but im worried it might be "cheating" as it strays away from the question a bit:

{
    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));
    });
}

The easiest way is to use Map#merge() :

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

after that, m will hold strings as keys and occurrences as values:

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

By using Collectors in streams:

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

So, if you have something like this:

        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())));

output will be:

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

I would use the groupingBy to return a map of counts.

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

to print these as well you can do

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM