FIZZBUZZ Solution in Java 8

Here is the FizzBuzz Solution in java 8 with different methods,

Here is the Before Java 8, simple solution:


public static void main(String[] args){
  for(int i= 1; i <= 20; i++){
   if(i % 15 == 0){
    System.out.println("FizzBuzz");
   }else if(i % 3 == 0){
    System.out.println("Fizz");
   }else if(i % 5 == 0){
    System.out.println("Buzz");
   }else{
    System.out.println(i);
   }
  }
 }


Now, Using Stream API, here different methods to display solved fizzbuzz solution,

Method1:
public static void main(String[] args) {
         fizzBuzzDisplay(1, 20;
  }
  private static void fizzBuzzDisplay(int i, int j) {
    // TODO Auto-generated method stub
           IntStream.rangeClosed(i,j)
                          .mapToObj(Test::transformNr)
                          .forEach(System.out::println);
   }

Method 2:
public static void main(String[] args) {
  // TODO Auto-generated method stub
  IntStream.rangeClosed(1, 20).mapToObj(num -> getWordForNum(num).orElse(Integer.toString(num)))
  .forEach(System.out::println);
 }
 private static Optional<String> getWordForNum(int num) {
  String word = "";
  if (isDiv(3).test(num))
   word += "Fizz";
  if (isDiv(5).test(num))
   word += "Buzz";
  return "".equals(word) ? Optional.empty() : Optional.of(word);
 }

 private static IntPredicate isDiv(int factor) {
  return arg -> (arg % factor) == 0;
 }

Method 3:
public static void main(String[] args) {
  // TODO Auto-generated method stub
  IntStream.rangeClosed(1, 20).mapToObj(A::fizzBuzz).forEach(System.out::println);
 }
 public static String fizzBuzz(int number) {
  if (number % 3==0 && number % 5 == 0) {
   return "FizzBuzz";
  } else if (number % 3 == 0) {
   return "Fizz";
  } else if (number % 5 == 0) {
   return "Buzz";
  }
  return Integer.toString(number);
 }

Method 4:
public static void main(String[] args) {
  // TODO Auto-generated method stub
  IntStream.range(1, 20)
        .mapToObj(n -> {
            if (n % 15 == 0) return "FizzBuzz";
            else if (n % 3 == 0) return "Fizz";
            else if (n % 5 == 0) return "Buzz";
            else return n;
        }).forEach(System.out::println);
 }

Mehtod 5:
public static void main(String[] args) {
  // TODO Auto-generated method stub
  IntStream.range(1, 20)
        .boxed()
        .map(x -> x+": " + (x%3==0? "Fizz": "") + (x%5==0? "Buzz": ""))
        .forEach(System.out::println);
 }

Output:

1
2
fizz
4
buzz
fizz
7
8
fizz
buzz
11
fizz
13
14
fizzbuzz
16
17
fizz
19
buzz

Happy Coding !!!

Print all the names of student in alphabetical order by gender in java 8 using Stream API

This question is some tricky, you have to create enum and student class then sorted the predefined condition in question.

Enum of Gender
public enum Gender {
 MALE,FEMALE;

}


Person Class with getter , setter and override to string method.
public class Person {
 
 public Gender getGender() {
  return gender;
 }
 public void setGender(Gender gender) {
  this.gender = gender;
 }
 public Person(String fn, String ln, Gender g){
  
  this.fName=fn;
  this.lName=ln;
  this.gender=g;
  
 }
 public String getfName() {
  return fName;
 }
 public void setfName(String fName) {
  this.fName = fName;
 }
 public String getlName() {
  return lName;
 }
 public void setlName(String lName) {
  this.lName = lName;
 }
 public String fName;
 public String lName;
 public Gender gender;
 
 public String getName(){
  return getfName()+" "+getlName();
 }
 
@Override
public String toString() {
 return  getfName()+" "+getlName();
}

}


and create person and display names

public static void main(String[] args) {
  // TODO Auto-generated method stub

    List<Person> persons=new ArrayList<>();
    persons.add(new Person("Arnolad", "Jones", Gender.MALE));
    persons.add(new Person("Zack", "Jones", Gender.MALE));
    persons.add(new Person("Mary", "Jones", Gender.FEMALE));
    persons.add(new Person("Anna", "Jones", Gender.FEMALE));
    
    System.out.println(persons.stream()
                        .sorted((p1,p2)->p1.getName().compareTo(p2.getName()))
                        .collect(Collectors.groupingBy(Person::getGender))
                        
      );
    
    
 }


Output:
{FEMALE=[Anna Jones, Mary Jones], MALE=[Arnolad Jones, Zack Jones]}

Happy Coding!!!


Combine different list in to Set(single list) in Java 8 using Stream API

Combine the different list in to single list in java, there should be used in java 8 Creating a stream pipeline that transforms a list of sets (of type String) into the union of those
sets. Make use of the reduce method for streams.
Example:
Orginal list [{“A”, “B”}, {“D”}, {“1”, “3”, “5”}] to the
Final Set
{“A”, “B”, “D”, “1”, “3”, “5”}.

Code looks like:
public class Union {

    public static void main(String[] args) {
        List<Set<String>> list = new ArrayList<>();
        Set<String> set1 = new LinkedHashSet<>(Arrays.asList(new String[]{"A", "B"}));
        list.add(set1);

        Set<String> set2 = new LinkedHashSet<>(Arrays.asList(new String[]{"D"}));
        list.add(set2);

        Set<String> set3 = new LinkedHashSet<>(Arrays.asList(new String[]{"1", "2", "3"}));
        list.add(set3);

        System.out.println("input: " + list);

        System.out.println("output:" + combinedList(list));

    }

    public static Set<String> combinedList(List<Set<String>> sets) {
        Optional<Set<String>> stream = sets.stream().reduce((t, u) -> {
            t.addAll(u);
            return t;
        });

        return stream.get();
    }
}



Happy Coding !!!

Sub List or partition list according to index in java 8 using Stream API

Question is like this, Create a method Stream<String> streamSection(Stream<String> stream, int m, int n) which extracts a substream from the input stream stream consisting of all elements from position m to position n , inclusive; you must use only Stream operations to do this. You can assume 0 <= m <= n .

Solution:
public class Section {

    public static Stream<String> streamSection(Stream<String> stream, int m, int n) {

        return stream.skip(m).limit(n - m + 1);
        

    }

    public static void main(String[] args) {

        System.out.println(streamSection(nextStream(), 0, 3).collect(Collectors.joining(", ")));
        System.out.println(streamSection(nextStream(), 2, 5).collect(Collectors.joining(", ")));
        System.out.println(streamSection(nextStream(), 7, 8).collect(Collectors.joining(", ")));
    }

    //support method for the main method -- for testing
    private static Stream<String> nextStream() {
        return Arrays.asList("aaa", "bbb", "ccc", "ddd", "eee", "fff", "ggg", "hhh", "iii").stream();

    }

}

Output:
aaa, bbb, ccc
eee, fff, ggg, hhh, iii
ccc, ddd, eee, fff, ggg, hhh


Happy Coding !!!

Print Square in Java Using Lambda or Stream API

Creates an IntStream using the iterate method. The method prints to the console the
first num squares. For instance, if num = 4, then your method would output 1, 4, 9, 16. Note:
You will need to come up with a function to be used in the second argument of iterate .


public class Test {

 public static void main(String[] args) {
  // TODO Auto-generated method stub

   System.out.println(printSSquare(5));
  //printSSquare(5).forEach(System.out::print);
    printUsingSream(5);
    
    
 }
 
 //Using java 8
 private static void printUsingSream(int ns) {
  // TODO Auto-generated method stub
  IntStream intS=IntStream.iterate(1, n->n+1).map(i->i*i).limit(ns);
  intS.forEach(System.out::println);
  
  
 }

    // Old techniques , Previous java 8
 private static List<Integer> printSSquare(int i) {
  
  List<Integer> test= new ArrayList<>();
  // TODO Auto-generated method stub
  for (int j = 1; j <= i; j++) {
   test.add(j*j);
   
  }
  return test;
 }

}




Output :

[1, 4, 9, 16, 25]
1
4
9
16
25

Happy Coding !!!