How to find the Stream is Primitive or Wrapper?

public class PrimStreams {
    public static void main(String[] args) {
        List<Integer> arrReviews1 = List.of(8, 9, 8 , 6, 2, 7, 6);
        System.out.println(arrReviews1.stream());

        int[] arrReviews2 = {8, 9, 8 , 6, 2, 7, 6};
        System.out.println(Arrays.stream(arrReviews2));

        System.out.println("----------Wrapper Streams Starts----------");
        System.out.println(arrReviews1.stream().reduce(Integer::sum));
        System.out.println(arrReviews1.stream().reduce(Integer::min));
        System.out.println(arrReviews1.stream().reduce(Integer::max));
        System.out.println(arrReviews1.stream().mapToInt(Integer::intValue).average().orElse(Double.NaN));

        System.out.println("----------Primitive Streams Starts----------");
        System.out.println(Arrays.stream(arrReviews2).sum());
        System.out.println(Arrays.stream(arrReviews2).min());
        System.out.println(Arrays.stream(arrReviews2).max());
        System.out.println(Arrays.stream(arrReviews2).average());
    }
}

In the below output you may see the wrapper class stream would be printed as ReferencePipeline whereas primitive stream would be displayed as IntPipeline. The above code contains doing some basic operation in both primitive and wrapper stream. If the stream is primitive type it would be easy to carry out operation over stream and more memory efficient since there would be no boxing and unboxing involved
Output

java.util.stream.ReferencePipeline$Head@1d251891
java.util.stream.IntPipeline$Head@2133c8f8
----------Wrapper Streams Starts----------
Optional[46]
Optional[2]
Optional[9]
6.571428571428571
----------Primitive Streams Starts----------
46
OptionalInt[2]
OptionalInt[9]
OptionalDouble[6.571428571428571]

How to create a primitive stream of Int?

  IntStream arrReviews3 = IntStream.of(8, 9, 8 , 6, 2, 7, 6);

Basic Operations in primitive stream of Int?

  1. range – Considers nos in specific range.range doesnot takes upper limit no.To address that rangeClosed is used
  2. iterate– Iterate helps in iterating till a particular range by taking Initial and urnaryOperator as params. The default behaviour of Iterator is endless loop.To stop after particular limit like one we did in range we should use limit function.
  3. peek– peek helps going through the values in stream without making any changes. This method exists mainly to support debugging, where you want to see the elements as they flow past a certain point in a pipeline
  4. boxed– boxed will help in boxing primitive to wrapper while collecting the values in to a list.
IntStream arrReviews = IntStream.of(8, 9, 8 , 6, 2, 7, 6);

        System.out.println("----------Stream printing Range of no ----------");

        System.out.println("range doesnot include last no 10 so sum is from 1 to 9 - " + IntStream.range(0,10).sum());
        System.out.println("rangeClosed would include last no 1 to 10 - " + IntStream.rangeClosed(0,10).sum());

        System.out.println("Using Peek we can look at nos in stream");
        System.out.println(IntStream.rangeClosed(0,10)
                                    .peek(System.out::println)
                                    .sum());

        System.out.println("iterate helps in iterating till a specific value");
        System.out.println(IntStream.iterate(1,e->e+1)
                                    .peek(System.out::println)
                                    .limit(10)
                                    .sum());

        System.out.println("iterate helps in iterating till a specific value");
        System.out.println(IntStream.iterate(1,e->e+2)
                                    .peek(System.out::println)
                                    .limit(10)
                                    .sum());

        System.out.println("Iterating over range and collecting in a list");
        List<Integer> arrIntegStream = IntStream.iterate(1,e->e+1)
                                                .peek(System.out::println)
                                                .limit(10)
                                                .boxed()
                                                .collect(Collectors.toList());
        System.out.println(arrIntegStream);

Finding Factorial of No of range 5

public class Factorial {
    public static void main(String[] args) {
        System.out.println(IntStream.rangeClosed(1,5).reduce(1, (x,y)->x*y));

        int i,fact=1;
        int number=5;//It is the number to calculate factorial
        for(i=1;i<=number;i++){
            fact=fact*i;
        }
        System.out.println(fact);
    }
}

Basic String Operation in Streams

  1. Join strings in a list using Collectors.joining
  2. Make Array of String using split. Split would return Array Stream
  3. Apply transformation in elements in list using replaceAll
  4. To flatten the Array Stream in the List use flatMap
  5. Get rid of particular element in List of String using removeIf
  6. Use replaceAll to carry Out Transformation similar to map()
  7. Use peek to support debugging, where you want to see the elements as they flow past a certain point in a pipeline
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class StringOps {
    public static void main(String[] args) {
        List<String> arrSkills = List.of("Core Java", "Core Spring", "Spring MVC", "Spring Security", "Spring Boot", "RestAPI");

        System.out.println("-----Join Elements in List using Seperator - [,]---------");
        String skills = arrSkills.stream().collect(Collectors.joining(","));
        System.out.println("Skills are "+ skills);

        System.out.println("-----Split String and Store in String Array---------");
        String[] arrSkillList = skills.split(",");
        Arrays.stream(arrSkillList).forEach(System.out::println);

        System.out.println("-----Convert to UpperCase---------");
        List<String> arrModSkills = new ArrayList(arrSkills);
        arrModSkills.replaceAll(str -> str.toUpperCase());
        arrModSkills.forEach(System.out::println);

        System.out.println("-----Using flatMap to flatten Arrays of Stream and Getting Distinct Location---------");
        List<String> arrLocation = List.of("Madras,Mumbai,Bangalore", "Madras,Kolkatta,Delhi", "Delhi,Madras");
        List allLocations = arrLocation.stream()
                                       .map(location->location.split(","))
                                       .peek(loc-> System.out.println(loc))
                                       .flatMap(Arrays::stream)
                                       .distinct()
                                       .collect(Collectors.toList());

        allLocations.stream()
                    .map(loc->replaceMadras(loc.toString()))
                    .forEach(System.out::println);

        System.out.println("------------Remove Particular Location using removeIf------------");
        allLocations.removeIf(loc->loc.equals("Delhi"));
        allLocations.forEach(loc-> System.out.println(loc));
    }

    private static String replaceMadras(String location){
        if(location.equals("Madras"))
            return "Chennai";
        else
            return location;
    }
}

Converting Multiple List into Single List

public class StreamMisc {
    public static void main(String[] args) {
        List<List<String>> arrSkills = new ArrayList<>();
        arrSkills.add(Arrays.asList("Java", "C++", "C#"));
        arrSkills.add(Arrays.asList("HTML", "CSS"));
        arrSkills.add(Arrays.asList("SQL", "MySQL"));
        arrSkills.add(Arrays.asList("Azure"));

        List<String> arrAllSkills = arrSkills.stream().reduce(new ArrayList<>(), (a, b) -> {
            a.addAll(b);
            return a;
        });

        arrAllSkills.forEach((skill) -> System.out.print(skill + ","));
    }
}

Output

Java,C++,C#,HTML,CSS,SQL,MySQL,Azure

Comments are closed.