Java count occurrence of each item in an array
You could use a MultiSet
from Google Collections/Guava or a Bag
from Apache Commons.
If you have a collection instead of an array, you can use addAll()
to add the entire contents to the above data structure, and then apply the count()
method to each value. A SortedMultiSet
or SortedBag
would give you the items in a defined order.
Google Collections actually has very convenient ways of going from arrays to a SortedMultiset
.
Counting occurrences of integers in an array
What I have to say is, it took me a while to figure out what the two variables count
and countNum
represent for, maybe some comments are needed. But finally I find out the bug.
Suppose input ten numbers are: 5, 6, 7, 8, 5, 6, 7, 8, 5, 6
After sort, numList
is : 5, 5, 5, 6, 6, 6, 7, 7, 8, 8
The array count
returned by occurrences()
should be: [1, 2, 3, 1, 2, 3, 1, 2, 1, 2]
Actually the only useful numbers in this result array are:
count[2]: 3 count number for numList[2]: 5
count[5]: 3 count number for numList[5]: 6
count[7]: 2 count number for numList[7]: 7
count[9]: 2 count number for numList[9]: 8
The other numbers, like the first two numbers 1, 2
before 3
, are only used to calculate the sum occurrences incrementally, right? So, your loop logic should be changed as following:
remove the first
if
code block:if (num == 0)
{
if (count[num] <= 1)
System.out.println (numList[num] + " occurs " + count[num] + " time");
if (count[num] > 1)
System.out.println (numList[num] + " occurs " + count[num] + " times");
}Change the second
if
condition to:if ((num + 1) == MAX_NUM || numList[num] != numList[num + 1]) {
......
}
After this, your code should work well as expected.
BTW, you really don't need to do it so intricately. Just try HashMap
:)
Java count occurrence of each element in an integer array
For the latter question, you have to change
.forEach((k, v) -> if(v.size() > 1) System.out.println(k+" "+v.size()));
to
.forEach((k, v) -> {if(v.size() > 1) System.out.println(k+" "+v.size());});
For the first part, it's not clear why you need the first collect
followed by a second Stream
pipeline.
If the purpose was to convert an IntStream
to a Stream<Integer>
, use boxed()
:
Arrays.stream(arr)
.boxed()
.collect(Collectors.groupingBy(s -> s))
.forEach((k, v) -> System.out.println(k+" "+v.size()));
As Dici suggested, you can also chain Collectors to group each number with its number of occurrences :
Map<Integer,Integer> occurrences =
Arrays.stream(arr)
.boxed()
.collect(Collectors.groupingBy(s -> s, Collectors.counting()));
Java count occurrence of each item in an sorted array
This would be a good place for a HashMap, the key would be the Word, and the value the Number of times it occurs. The Map.containsKey
and Map.get
methods are constant time lookups which are very fast.
Map<String,Integer> map = new HashMap<String,Integer>();
for (int i = 0; i < patternsTest.length; i++) {
String word=patternsTest[i];
if (!map.containsKey(word)){
map.put(word,1);
} else {
map.put(word, map.get(word) +1);
}
}
As a side benefit you don't even need to sort beforehand!
Counting occurrences in array java
public static void main(String[] args){
int[] arryNum = new int[] { 4, 4, 4, 3, 4, 5, 4, 3, 4, 4, 4, 5, 4, 5, 5, 5, 4, 3, 2, 15, 4,
3, 4, 6, 4, 3, 4, 5, 4, 2, 4, 5, 4, 3, 2, 5, 4, 3, 5, 4, 0, 4, 3, 4, 5, 4, 3, 0, 4,
5, 4, 3, 5, 4, 2, 3, 2, 3, 4 };
Map<Integer, Integer> lookup = new HashMap<>();
for (int key : arryNum) {
if(lookup.containsKey(key)) {
lookup.put(key, lookup.get(key) + 1);
} else {
lookup.put(key, 1);
}
}
for (Integer keys : lookup.keySet()) {
System.out.println(keys + " Found " + lookup.get(keys) + " Times");
}
}
Counting the Occurrence of a String in an Array of Strings
You can use indexOf
to count all occurrences of a string, but you have to use the form that takes the index at which to start counting, which will be the previously found index plus the length of the query string.
public static int countOccurence2(String[]arr, String n)
{
int count = 0;
for(int i = 0; i < arr.length; i++)
{
int idx = arr[i].indexOf(n);
while(idx != -1)
{
count++;
idx = arr[i].indexOf(n, idx+n.length());
}
}
return count;
}
Which produces the desired output: 4,1,0
Related Topics
Date Object Simpledateformat Not Parsing Timestamp String Correctly in Java (Android) Environment
Findviewbyid Returns Null in a Dialog
Best Way to Compare Dates in Android
Error: Unable to Load Installed Packages Just Now
Exception in Thread "Main" Java.Lang.Noclassdeffounderror: Org/Openqa/Selenium/Webdriver
Converting a Date String to a Datetime Object Using Joda Time Library
How to Access an Iteration-Counter in Java's For-Each Loop
How to Terminate Scanner When Input Is Complete
How to Do a Junit Assert on a Message in a Logger
How to Read an External Properties File in Maven
How to Count the Number of Matches for a Regex
MAC Os X and Multiple Java Versions
Why Is String.Chars() a Stream of Ints in Java 8
What Is the Default Access Specifier in Java