Count int occurrences with Java8
Try:
Map<Integer, Long> counters = persons.stream()
.collect(Collectors.groupingBy(p -> p.getBirthday().getMonthValue(),
Collectors.counting()));
Java 8 : Count the occurrence of digit 4 in the given int array
First, you need to obtain a stream from the given array of int[]
. You can do it either by using the static method IntStream.of
, or with Arrays
utility class and it's method stream()
.
Both will give you an IntStream
- a stream of int
primitives. In order to collect stream elements into a list you need to convert it to a stream of objects. For that you can apply method boxed()
on the stream pipeline and each int
element will get wrapped with Integer
object.
In order to find all elements in the given list that contain a target digit (4
), you can turn the target digit into a string and then apply a filter
based on it.
public static List<Integer> findOccurrencesOfDigit(List<Integer> source,
int digit) {
String target = String.valueOf(digit);
return source.stream()
.filter(n -> String.valueOf(n).contains(target))
.collect(Collectors.toList());
}
main()
public static void main(String[] args) {
int[] nums = {48,44,4,88,84,16,12,13};
System.out.println(findOccurrencesOfDigit(nums, 4));
}
Output
[48, 44, 4, 84]
Note: method filter()
expects a Predicate
(a function represented by a boolean condition, that takes an element and return true
of false
)
Your attempt to create a predicate filter(n -> n % 10)
is incorrect syntactically and logically. n % 10
doesn't produce a boolean value, it'll give the right most digit of n
.
If you want to use modulus (%
) operator to create a predicate, you have to divide the element by 10
in a loop until it'll not become equal to 0
. And check before every division weather remainder is equal to the target digit. It could be done like that:
public static boolean containsDigit(int candidate, int digit) {
boolean flag = false;
while (candidate != 0) {
if (candidate % 10 == digit) {
flag = true;
break;
}
candidate /= 10; // same as candidate = candidate / 10;
}
return flag;
}
You can utilize this method inside a lambda expression like that (note: it's a preferred way to avoid multiline lambda expressions by extracting them into separate methods)
filter(n -> containsDigit(n, digit))
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()));
Counting occurrences in a list with Java 8
You can use a Stream<PDFDataItem>
with Collectors.groupingBy()
Collector
to group the PDFDataItem
instances by the value
property and then count the number of elements in each group using the Collectors.counting()
Collector
.
Map<Double,Long> valueCounts =
pdfList.stream()
.collect(Collectors.groupingBy(PDFDataItem::getValue,Collectors.counting()));
create map of int occurrences using Java 8
IntStream has one method collect
where the second argument operates on an int
not an Object. Using boxed()
turns an IntStream
into a Stream<Integer>
Also counting()
returns a long
.
Map<Integer, Long> result = IntStream.range(0, 100).boxed()
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
Counting word occurence with arrays stream in Java 8
String sentence = "The cat has black fur and black eyes";
String[] bites = sentence.trim().split("\\s+");
String in = "black cat";
long i = Stream.of(bites).filter(e->(Arrays.asList(in.split("\\s")).contains(e))).count();
System.out.println(i);
Count occurrences of a String in a List, then sort the result - Java 8
You can get the desired output if you use a TreeMap
instead of the default HashMap
when you create the Map
like this:
Map<String, Long> employeeFirstNameCount = employees.stream()
.collect(Collectors.groupingBy(Employee::getFirstName,
TreeMap::new,
Collectors.counting()));
The java.util.TreeMap
uses the natural ordering of its keys (that is enough for what you need) or you can provide a custom Comparator
Note I use the lambda expression Employee::getFirstName
instead of p -> p.getFirstName()
, but both produce the same result.
How can I count occurrences with groupBy?
I think you're just looking for the overload which takes another Collector
to specify what to do with each group... and then Collectors.counting()
to do the counting:
import java.util.*;
import java.util.stream.*;
class Test {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("Hello");
list.add("Hello");
list.add("World");
Map<String, Long> counted = list.stream()
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
System.out.println(counted);
}
}
Result:
{Hello=2, World=1}
(There's also the possibility of using groupingByConcurrent
for more efficiency. Something to bear in mind for your real code, if it would be safe in your context.)
Related Topics
How to Run MySQL In-Memory for Junit Test Cases
Mockito: Mock Private Field Initialization
Differencebetween Synchronized on Lockobject and Using This as the Lock
Java Erasure with Generic Overloading (Not Overriding)
Unit Testing with Mockito for Constructors
Spring Boot Actuator Without Spring Boot
Why Aren't Integers Cached in Java
Incompatible Jvm in Ggts (Eclipse) and Java 1.8
Efficient Way to Divide a List into Lists of N Size
Tomcat 7 "Severe: a Child Container Failed During Start"
How to Clear Permgen Space Error in Tomcat
Why Are Variables Declared with Their Interface Name in Java
Why in Java Enum Is Declared as Enum<E Extends Enum<E>>