Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the most common String in ArrayList()

Is there a way to find the most common String in an ArrayList?

ArrayList<String> list = new ArrayList<>();
list.add("test");
list.add("test");
list.add("hello");
list.add("test");

Should find the word "test" from this list ["test","test","hello","test"]

like image 775
EspenG Avatar asked Apr 10 '14 13:04

EspenG


People also ask

How do you count occurrences in ArrayList in Java?

Suppose we have an elements in ArrayList, we can count the occurrences of elements present in a number of ways. This data structure uses hash function to map similar values, known as keys to their associated values. Map values can be retrieved using key as it contains key-value pairs.

How do you find a specific element in an ArrayList?

The index of a particular element in an ArrayList can be obtained by using the method java. util. ArrayList. indexOf().


2 Answers

In statistics, this is called the "mode". A vanilla Java 8 solution looks like this:

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

Which yields:

test=3

jOOλ is a library that supports mode() on streams. The following program:

System.out.println(
    Seq.of("test","test","hello","test")
       .mode()
);

Yields:

Optional[test]

(disclaimer: I work for the company behind jOOλ)

like image 117
Lukas Eder Avatar answered Sep 17 '22 10:09

Lukas Eder


As per question, Specifically just to get word, not the number of times (i.e. value of key).

String mostRepeatedWord 
    = list.stream()
          .collect(Collectors.groupingBy(w -> w, Collectors.counting()))
          .entrySet()
          .stream()
          .max(Comparator.comparing(Entry::getValue))
          .get()
          .getKey();
like image 36
ChandraBhan Singh Avatar answered Sep 20 '22 10:09

ChandraBhan Singh