Problem:- How to count the number of occurrences of an element in a List using Java 8
Java code:-
package com.codeforsolution.java8;
/*//Write a program to count the number of occurrences of an elements in a list.
*
*/
package com.codeforsolution.java8;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class FindOccurrences {
public static void main(String[] args) {
List<String> lists = Arrays.asList("apple", "banana", "apple", "grapes", "banana", "orange", "apple");
Map<String> long=""> listWithOccurrences = lists.stream().collect(Collectors.groupingBy(e -> e, Collectors.counting()));
System.out.println(listWithOccurrences);
}
}
Output:- {orange=1, banana=2, apple=3, grapes=1}
Problem:- Write a program to print the count of each character in a String?
Java code:-
/*
* Write a program to count the number of occurrences from the string.
*/
package com.codeforsolution.logical.java8;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
public class FindOccurrencesFromString {
public static void main(String[] args) {
String str = "Hello Everyone, This is from codeforsolution";
String str1 =str.replaceAll("[^a-zA-Z]+", "");
System.out.println(str1);
Map<Character,Long> strOccurrences1 = str.replaceAll("[^a-zA-Z]+", "").codePoints().mapToObj(e->(char)e).collect(Collectors.groupingBy(e->e,Collectors.counting()));
System.out.println(strOccurrences1);
Map<Character,Long> strOccurrences2 = str.replaceAll("[^a-zA-Z]+", "").codePoints().mapToObj(e->(char)e).collect(Collectors.groupingBy(Function.identity(),Collectors.counting()));
System.out.println(strOccurrences2);
}
}