Posts

Showing posts with the label Streams

Java 8 IntStream Examples

In Java, `IntStream` is a part of the java.util.stream package and represents a stream of primitive integers. It's designed to work with the functional programming features introduced in Java 8, allowing you to perform aggregate operations on sequences of elements. Here are some examples of using `IntStream`: Example 1: Creating IntStream import java.util.stream.IntStream; public class IntStreamExample {     public static void main(String[] args) {         // Create an IntStream using range         IntStream.range(1, 6).forEach(System.out::println); // Prints 1, 2, 3, 4, 5                  // Create an IntStream using rangeClosed         IntStream.rangeClosed(1, 5).forEach(System.out::println); // Prints 1, 2, 3, 4, 5     } } Example 2: Operations on IntStream import java.util.stream.IntStream; public class IntStreamExample {     public static void ma...

Java Program to Count the Occurrences of Each Character in String | Java Inspires

Image
Java Program to Count the Occurrences of Each Character in String In this post, we will write a simple java program to count the occurrences of each character in a given string. Here, first we will take a string and then create a character stream by spliting with "", and collect each character and count by grouping using java 8 stream features. package com . javainspires . examples ; import java.util.Arrays ; import java.util.LinkedHashMap ; import java.util.Map ; import java.util.function.Function ; import java.util.stream.Collectors ; public class ExampleMain { public static void main ( String [] args ) { String name = "Java Inspires Java Inspires" ; Map < String , Long > result = Arrays . stream ( name . split ( "" )) . collect ( Collectors . groupingBy ( Function . identity (), Collectors . counting ())); System . out . println ( res...