Java 8 stream API coding questions

 import java.util.*;

import java.util.stream.Collectors;

import java.util.function.Function;

import java.util.stream.*;

import java.time.*;

public class Main {

    public static void main(String[] args) {

      

      //seperate odd and even 

     List<Integer> list = Arrays.asList(1,4,7,8,0,9,3);


  

     List<Integer> odd=  list.stream()

     .filter(x->x%2==1)

     .collect(Collectors.toList());

     List<Integer> even = list.stream().filter(x->x%2==0).collect(Collectors.toList());

    //using partioning By 

Map<Boolean,List<Integer>> sep = list.stream().collect(Collectors.partitioningBy(x->x%2==0));

      System.out.println("odd :"+ odd + "even:"+even );

      System.out.println("odd: "+ sep.get(true));

      System.out.println("even: "+ sep.get(false));

      

      //  remove dulipcates from a list

      List<Integer> list1 = Arrays.asList(1,1,2,2,3,3,4,4,5,6,7,77,8);

      List<Integer> l=list1.stream().distinct().collect(Collectors.toList());

      System.out.println(l);

      //frequency of each character in String 

      String str = "abcdbcebfrf";

      Map<Character, Long> map = str.chars()

                               .mapToObj(c->(char)c)

                               .collect(Collectors.groupingBy(c->c, Collectors.counting()));

      Map<Character, Long> map1 = str.chars()

                               .mapToObj(c->(char)c)

                               .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));

      System.out.println(map1);

      //frequency of each element in an Arrays

      int []arr = {1,3,4,5,2,2,2,2,3,3,6,7,7};

      Map<Integer,Long> map3  = Arrays.stream(arr)

                              .mapToObj(x->x)

                              .collect(Collectors.groupingBy(x->x, Collectors.counting()));

      System.out.println(map3);

      //sort a list in reverse order 

      List<Integer> list4 = Arrays.asList(1,5,2,3,4,7,2,3,0,9,12,9)

                            .stream()

                            .sorted((a,b)->b-a) // sorted(Comparator.reverseOrder())

                            .collect(Collectors.toList());

      System.out.println(list4);

      //join list of strings with prefix, suffix and delimeter

       List<String> s = Arrays.asList("jaya","priya","diya");

       String ans= s.stream()

        .collect(Collectors.joining(",","[","]")); //.joining(delimeter,pref,suffix)

        System.out.println(ans);

        

       //print multiple of 5 from the list

       Arrays.asList(2,4,5,6,7,8,10,2,15,0,20)

       .stream()

       .filter(x->x%5==0)

       .forEach(System.out::println);

       

       //maximum & minimum in a list

       list4.stream().max(Integer::compareTo).ifPresent(System.out::println);

       list4.stream().min(Integer::compareTo).ifPresent(System.out::println);

       

              //merge two unsorted arrays into single sorted array

       int [] a1 = {3,5,1,2,9,0};

       int [] a2 = {7,1,8,9,0};

       int[] result= IntStream.concat(Arrays.stream(a1),Arrays.stream(a2))

                      .sorted()

                      .peek(System.out::print)

                      .toArray();

        System.out.println(Arrays.toString(result));

        

        //Anagram program in java

        String ss = "Jaya";

        String ana = "Ajay";

        String ss1 = ss.toUpperCase()

                     .chars()

                     .sorted()

                    .mapToObj(c-> String.valueOf((char)c))

                    .collect(Collectors.joining());

       String ana1 = ana.toUpperCase()

                      .chars()

                      .sorted()

                      .mapToObj(c->String.valueOf((char)c))

                      .collect(Collectors.joining());

        System.out.println(ss1.equals(ana1));

        

        //sum of all digits of a Number

        int num = 1234;

        int sum = String.valueOf(num)

                  .chars()

                  .map(c->c-'0')

                  .sum();

        System.out.println(sum);

        

        //3 max and min in a list

        List<Integer> list5 = Arrays.asList(1,3,4,5,6,7,8,8,9,9,0);

        list5.stream()

        .sorted()

        .limit(3).skip(2)

        .forEach(System.out::println);

        

        list5.stream().sorted((a,b)->b-a).limit(3).skip(2).forEach(System.out::println);

        

        //second largest number in an integer Arrays

        int []arr2 = {2,4,5,6,6,7,1,2,5,9,10,12};

        Arrays.stream(arr2)

        .boxed()

        .sorted((a,b)->b-a)

        .skip(1).findFirst().ifPresent(System.out::println);

        

        //sort list of strings in increasing num. of their length

        List<String> s5 = Arrays.asList("diya", "subhyata", "ram","ro", "kyu");

        List<String> s6 = s5.stream()

                          //.sorted((a,b)->b.length()-a.length())  --decreasing

                          .sorted(Comparator.comparing(String::length))

                          .collect(Collectors.toList());

        System.out.println(s6);

        

        //common elements between two arrays

        //  int [] a1 = {3,5,1,2};

      //    int [] a2 = {7,1,8,9,0};

          Arrays.stream(a1)

          .filter(x-> Arrays.stream(a2)

          .anyMatch(y-> y==x))

          .forEach(System.out::println);

        //another methos

        list1.stream().filter(list5::contains).forEach(System.out::println);

        

        //sum and average of all elements in an arrray

        int sum1 = Arrays.stream(a1).sum();

        double avg = Arrays.stream(a1).average().getAsDouble();

        System.out.println(" sum : "+ sum1 + " avg : " + avg);

        

        //reverse each word of a string 

        List<String> reverse = s5.stream()

                        .map(word -> new StringBuilder(word).reverse().toString())

                        .collect(Collectors.toList());

      System.out.println(reverse);

      

      //sum of first 10 natural number

      int sumNat= IntStream.range(1,11).sum();

      System.out.println(sumNat);

      //reverse an integer Array

      IntStream.rangeClosed(1,a1.length)

      .map(i->a1[a1.length-i])

      .forEach(System.out::println);

      //find String which start with number

      List<String> s7 = Arrays.asList("10priya","8ndlm", "7wdjnkdj","9");

      s7.stream()

      .filter(s8->Character.isDigit(s8.charAt(0)))

      .forEach(System.out::println);


        //paindrom program in java 8

       String s9 = "madam";

       Boolean paindrom = IntStream.range(0, s9.length()/2)

       .noneMatch(i->s9.charAt(i)!=s9.charAt(s9.length()-i-1));

       System.out.println(paindrom);

       

       //find duplicat elements from an array 

       Set<Integer> set = new HashSet<>();

       Set<Integer> duplicate =  Arrays.stream(arr2)

        .filter(i-> !set.add(i))

        .boxed()

        .collect(Collectors.toSet());

      System.out.println(duplicate);

      

      //last element of an Arrays

      int last = Arrays.stream(arr2).skip(arr2.length-1).findFirst().orElse(-1);

      System.out.println(last);

      

      //fibonaci series

      Stream.iterate(new int[]{0,1}, f  -> new int[] {f[1], f[0]+f[1]})

        .limit(10)

        .map(f->f[0])

        .forEach(System.out::println);

      

      //age of a person in year

      LocalDate birthday = LocalDate.of(2000,12,16);

      LocalDate today = LocalDate.now();

      int age = Period.between(birthday,today).getYears();

      System.out.println(age);

    }

    

}

Comments

Popular posts from this blog

Vaco Binary Simantics interview expeirence

Intellect Interview Experience

Google