Friday 7 July 2017

Selenium - Optional in Java 8--Streams filter(), findAny(), Maps and orElse() with compound conditions

Selenium java 8 optional, java optional if present, Optional isPresen,t and ifPresent, optional found.orElse, Optional findFirst(), max(), min(), Streams filter(), findAny(), Maps and orElse() with compound conditions


Selenium - Optional in Java 8


  • When Optional is used there will be no need for “Null Checks” and “NullPointerException” at run-time will not occur.
  • It may contain a value or it will be empty.
  • Optional Stream API contain methods such as “findAny”, “findFirst”, “max” and “min”
  • In selenium it will be used in scenarios such as the “DropDownBox” or “ListBox”



Prerequisite:


package streamFilters;

 public class Student {

    private String student;
    private int id;
    public int result2;

    public Student(String student, int id) {
        this.student = student;
        this.id = id;
    }

       public String getStudent() {
              return student;
       }

       public void setStudent(String student) {
              this.student = student;
       }

       public int getId() {
              return id;
       }



       public void setId(int id) {
              this.id = id;
       }

}


1. Optional Examples

package streamFilters;

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;

public class OptionalEg{

       public static void main(String[] args) {

               List<Student> students = Arrays.asList(
                       new Student("Kellby", 4),
                       new Student("rose", 5),
                       new Student("warner", 8),
                       new Student("RVS", 3),
                       new Student("SS", 13)
               );


               // Optional isPresent and ifPresent

               Optional<Student> result1 = students.stream().filter(x -> "RVS".equals(x.getStudent())).findAny();
               Optional<Student> result2 = students.stream().filter(y -> "SS".equals(y.getStudent())).findAny();
               Optional<String> result3 = Optional.empty();

               if (result1.isPresent()) {
                   System.out.println("Student name: "+ result1.get().getStudent()+" "+"Student ID: "+ result1.get().getId());

               } else {
                   System.out.println("Value not available.");
               }

                result1.ifPresent(g -> System.out.println("Student name: " +result1.get().getStudent()+ " "+"Student ID: " +result1.get().getId()));


               // E.g. found.orElse

                  String st1 = result1.orElse(new Student("No value",0)).getStudent();
                  String st2 = result2.orElse(new Student("No value",0)).getStudent();

                  System.out.println("The matched name is: "+st1);
                  System.out.println("The matched name is: "+st2);

           // If input value is empty o/p value would be empty

           System.out.println(result3.orElse("<Empty>"));            

             

           // Compound Conditions
     
           Optional<Student> result5 = students.stream().filter((z) -> "RVS".equals(z.getStudent()) && 3 == z.getId()).findAny();
           result5.ifPresent(g -> System.out.println("Student name: " +result5.get().getStudent()+ " "+"Student ID: " +result5.get().getId()));
   

              // E.g findFirst(), max(), min()

              Optional<Student> result4 = students.stream().findFirst();        
             System.out.println("First Student Name: "+ result4.get().getStudent() +" "+"First Student ID: "+ result4.get().getId());

           Optional<Student> max = students.stream().max(comparing(students));
           System.out.println("The Max student ID: " + max.get().getId());        

           Optional<Student> min = students.stream().min(comparing(students));
           System.out.println("The Min student ID: " + min.get().getId());        

       }

       private static Comparator<? super Student> comparing(Object object) {
              Comparator <Student> comparator = (p1, p2) -> Integer.compare(p1.getId(), p2.getId());
              return comparator;
       }

}

Output:

Student name: RVS Student ID: 3

Student name: RVS Student ID: 3

The matched name is: RVS

The matched name is: SS

<Empty>

Student name: RVS Student ID: 3

First Student Name: Kellby First Student ID: 4

The Max student ID: 13

The Min student ID: 3


2. Optional Map


package streamFilters;

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;

public class FilterMap {

       public static void main(String[] args) {

        List<Student> students = Arrays.asList(
                new Student("Kellby", 4),
                new Student("rose", 5),
                new Student("warner", 8),
                new Student("RVS", 3),
                new Student("SS", 13)
        );


        // Optional isPresent and ifPresent

        Optional<String> result1 = students.stream().filter(x -> "RVS".equals(x.getStudent())).map(Student::getStudent).findAny();
        Optional<Integer> result2 = students.stream().filter(y -> "RVS".equals(y.getStudent())).map(Student::getId).findAny();
        Optional<String> result3 = Optional.empty();

       

        if (result1.isPresent()) {
            System.out.println("Student name1: "+result1+" "+"Student ID: "+result2);
        } else {
            System.out.println("Value not available.");
        }    

        result1.ifPresent(g -> System.out.println("Student name1: "+result1+" "+"Student ID: "+result2));    


        // E.g. found.orElse      

        System.out.println("The matched name is: "+ result1.orElse("<Empty>") + "  Name would be Empty if value not matched");
        System.out.println("The matched id is: "+ result2.orElse(1) + "  Id would be one if value not matched");

        // As input value is empty o/p value would be empty

        System.out.println("When Empty object is pass: " + result3.orElse("<Empty>"));

        // E.g findFirst(), max(), min()

     
        Optional<String> result4 = students.stream().map(Student::getStudent).findFirst();
        Optional<Integer> result5 = students.stream().map(Student::getId).findFirst();
        System.out.println("First Student name: "+ result4 + "First Student id: "+ result5);

        Optional<Student> max = students.stream().max(comparing(students));
        System.out.println("The Max student ID: " + max.map(Student::getId));

        Optional<Student> min = students.stream().min(comparing(students));
        System.out.println("The Min student ID: " + min.map(Student::getId));  

    }    

       private static Comparator<? super Student> comparing(Object object) {
              Comparator <Student> comparator = (p1, p2) -> Integer.compare(p1.getId(), p2.getId());
              return comparator;
       }

}

Output:

Student name1: Optional[RVS] Student ID: Optional[3]

Student name1: Optional[RVS] Student ID: Optional[3]

The matched name is: RVS  Name would be Empty if value not matched

The matched id is: 3  Id would be one if value not matched

When Empty object is pass: <Empty>

First Student name: Optional[Kellby]

First Student id: Optional[4]

The Max student ID: Optional[13]

The Min student ID: Optional[3]

Tuesday 4 July 2017

Java8: Convert String To Integer and To Date

Java 8, string to integer, string to date, convert  date to different formats




package convert;

import java.text.DateFormat;
import java.text.ParseException;
import java.util.Date;
import java.util.Locale;
import java.text.SimpleDateFormat;

public class ConvertStringToIntAndToDate {

       public static void main(String[] args){

              // E.g. Integer.parseInt(), this converts to integer

              String number = "50";
              int result = Integer.parseInt(number);
              System.out.println("1.The string which is coonverted to int is : " + result);


              // E.g. Integer.valueOf(), this will return an integer object

              String number1 = "20";
              Integer result1 = Integer.valueOf(number1);
              System.out.println("2. The string which is converted to an integer object: " + result1);

           

              // Converts String to Date Format which is like Thu Dec 31 00:00:00 IST 1998

              try{

                     stringToDate ("July 03, 2017", "MMMM dd, yyyy");
                     stringToDate("31/12/2016", "dd/MM/yyyy");
                     stringToDate("12 31, 2000", "MM dd, yyyy");
                     stringToDate("Tue, jul 31 2017", "E, MMM dd yyyy");
                     stringToDate("Tue, jul 31 2017 23:37:50", "E, MMM dd yyyy HH:mm:ss");
                     stringToDate("30-jun-2017 23:37:50", "dd-MMM-yyyy HH:mm:ss");

              } catch (Exception e) {

                     System.out.println(e.getStackTrace());

              }

              // Convert date to different formats

              convertDatetoDiffFormat();

       }

     



    public static void stringToDate(String dateString,String dateFormat) throws ParseException{

       // Java 8 update

       DateFormat format = new SimpleDateFormat(dateFormat, Locale.ENGLISH);
       Date date = format.parse(dateString);
       System.out.println("String is converted to date: "+date);

     

    }


    public static void convertDatetoDiffFormat(){

       String format1=new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(new java.util.Date());
       System.out.println(format1);

    }



}









Output:



1.The string which is converted to INT is : 50

2. The string which is converted to an integer object: 20

String is converted to date: Mon Jul 03 00:00:00 IST 2017

String is converted to date: Sat Dec 31 00:00:00 IST 2016

String is converted to date: Sun Dec 31 00:00:00 IST 2000

String is converted to date: Mon Jul 31 00:00:00 IST 2017

String is converted to date: Mon Jul 31 23:37:50 IST 2017

String is converted to date: Fri Jun 30 23:37:50 IST 2017

Mon Jul 03 16:06:31 IST 2017

2017-07-03 16:06:32.011

Selenium- java 8- Example of Streams filter(), findAny(), Maps and orElse() with compound conditions

Selenium- java 8- Example of Streams filter(), findAny(), Maps and orElse() with compound conditions


Selenium- java 8- Example of Streams filter(), findAny(), Maps and orElse() with compound conditions


1.
package streamFilters;

public class Student {

    private String student;
    private int id;

    public Student(String student, int id) {
        this.student = student;
        this.id = id;
    }

public String getStudent() {
return student;
}

public void setStudent(String student) {
this.student = student;
}

public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}
 
 

}


2. Java 8: stream.filter() to filter a List, and .findAny().orElse (null) to return an object conditional.

package streamFilters;

import java.util.Arrays;
import java.util.List;

public class FindAnyOrElseNull{


public static void main(String[] args) {


       List<Student> students = Arrays.asList(
               new Student("Kellby", 4),
               new Student("rose", 5),
               new Student("warner", 8),
               new Student("RVS", 3),
               new Student("SS", 13)
       );

       Student result1 = students.stream()                      
               .filter(x -> "rose".equals(x.getStudent()))      
               .findAny()                                    
               .orElse(null);                                
     
if (result1==null){

System.out.println(result1);

       }else{
        System.out.println("Student name: "+result1.getStudent()+" "+"Student ID: "+result1.getId() );
       }

       System.out.println("Student name: "+result1.getStudent()+" "+"Student ID: "+result1.getId() );

       Student result2 = students.stream()
               .filter(x -> "SSS".equals(x.getStudent()))
               .findAny()
               .orElse(null);
     
if (result2==null){

System.out.println(result2);

       }else{
        System.out.println("Student name: "+result2.getStudent()+" "+"Student ID: "+result2.getId() );
       }

}


}

Output:

Student name: rose Student ID: 5
Null

3. Java 8:  Compound Conditions

package streamFilters;

import java.util.Arrays;
import java.util.List;


public class CompundConditions {

public static void main(String[] args) {

        List<Student> students = Arrays.asList(
                new Student("Kellby", 4),
                new Student("rose", 5),
                new Student("warner", 8),
                new Student("RVS", 3),
                new Student("SS", 13)
        );
     
        Student result1 = students.stream()
                .filter((y) -> "SS".equals(y.getStudent()) && 13 == y.getId())
                .findAny()
                .orElse(null);

if (result1==null){

System.out.println(result1);

        }else{
        System.out.println("Student name: "+result1.getStudent()+" "+"Student ID: "+result1.getId() );
        }


        //or like this
        Student result2 = students.stream()
                .filter((z -> "warner1".equals(z.getStudent()) && 8 == z.getId()))
                .findAny()
                .orElse(null);

if (result2==null){

System.out.println(result2);

        }else{
        System.out.println("Student name: "+result2.getStudent()+" "+"Student ID: "+result2.getId() );
        }

    }


}

Output:

Student name: SS Student ID: 13
Null


4. Java8: Filter and Map


package streamFilters;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class FilterMap {

public static void main(String[] args) {

        List<Student> students = Arrays.asList(
                new Student("Kellby", 4),
                new Student("rose", 5),
                new Student("warner", 8),
                new Student("RVS", 3),
                new Student("SS", 13)
        );

        String name = students.stream()
                .filter(x -> "RVS".equals(x.getStudent()))
                .map(Student::getStudent)                      
                .findAny()
                .orElse("");

        System.out.println("Student name : " + name);

        List<String> collect = students.stream()
                .map(Student::getStudent)
                .collect(Collectors.toList());

        System.out.println("********************  List Names:");
        collect.forEach(System.out::println);

    }

}

Output:
Student name : RVS
********************  List Names:
Kellby
rose
warner
RVS
SS

Sunday 2 July 2017

Selenium - Java8 - Streams, Filter, Collectors examples

 
Array, collectors, Filters, Java8, Streams, Selenium - Java8 - Streams, Filters, Collectors examples

 

Selenium - Java8 - Streams, Filters, Collectors examples

Code:

package sfcl;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class streamFilterCollectorList {

public static void main(String[] args) {

        List<String> nmaes = Arrays.asList("Anderson", "Paul", "Ahamed", "Ram");

        // change list to stream
        List<String> output = nmaes.stream() 
        // we are filtering out ram
                .filter(line -> !"Ram".equals(line))  
            // Stores the output and  changes streams to a List
                .collect(Collectors.toList());              

        Iterable<String> result;
        output.forEach(System.out::println);               
}
}

OutPut:



Selenium -Java – Retrieving the current date time and updating them in different formats

Java time, calendar, date and time, local date and time, update to different formats, -Java – Retrieving the current date time and updating them in different formats

Selenium -Java – Retrieving the current date time and updating them in different formats

Code:

package date;

import java.util.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.format.DateTimeFormatter;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Calendar;


public class DateTime {

    public static DateFormat simpleDF = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
    public static DateTimeFormatter dateTF = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
public DateTime(int i, int j, int k, int l, int m, int n) {
}

public static void main(String[] args) {
        Date date = new Date();
        System.out.println("1. Simple Date Format with date:     " +simpleDF.format(date));

        Calendar cal = Calendar.getInstance();
        System.out.println("2. Simple Date Format with calendar:  " +simpleDF.format(cal.getTime()));

        LocalDateTime now = LocalDateTime.now();
        System.out.println("3. Date Time Format with local time:  " +dateTF.format(now));

        LocalDate localDate = LocalDate.now();
        System.out.println("4. Date Time Format with local date:  " +dateTF.ofPattern("yyy/MM/dd").format(localDate));

        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(Calendar.getInstance().getTime());
        System.out.println("5. current date/time:                 " +timeStamp);
        
     
       
}

}

Output;