Monday, January 16, 2017

Collection.sort with multiple fields using Java 8

package com.java8.chapter1;

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import static java.util.Comparator.*;



 public class Example1 {

    public static void main(String[] args) {
        List<Employee> empList = getEmpList();


        // Before Java 8 
        empList.sort(new Comparator<Employee>() {

            @Override
            public int compare(Employee o1, Employee o2) {
                int res = o1.getDesignation().compareTo(o2.getDesignation());
                if (res == 0) {
                    return o1.getSalary() > o2.getSalary() ? 1 : o1.getSalary() < o2.getSalary() ? -1 : 0;
                } else {
                    return res;
                }

            }
        });
        for (Employee emp : empList) {
            System.out.println(emp);
        }
        System.out.println("---------------------------------------------------------------------------");

        // In Java 8

        empList.sort(comparing(Employee::getDesignation).thenComparing(Employee::getSalary));
        empList.stream().forEach(System.out::println);

    }
    private static List<Employee> getEmpList() {
        return Arrays.asList(new Employee("Lakshman A", "Consultent", 450000),
                new Employee("Chaitra S", "Developer", 250000), new Employee("Manoj PVN", "Developer", 250000),
                new Employee("Ramesh R", "Developer", 280000), new Employee("Suresh S", "Developer", 270000),
                new Employee("Jaishree", "Opearations HR", 350000));
    }
}

class Employee {
    private String fullName;
    private String designation;
    private double salary;

    public Employee(String fullName, String designation, double salary) {
        super();
        this.fullName = fullName;
        this.designation = designation;
        this.salary = salary;
    }

    public String getFullName() {
        return fullName;
    }

    public String getDesignation() {
        return designation;
    }

    public double getSalary() {
        return salary;
    }

    @Override
    public String toString() {
        return "Employee [fullName=" + fullName + ", designation=" + designation + ", salary=" + salary + "]";
    }

}

Friday, December 9, 2016

Java8 program to read data from file and displaying Statistics of data

 
Employees date of birth is stored in an file in the following format:

08/06/1984
29/5/1982
20/1/1989
17/5/1989
22nd October 1991
14th December 1991
20th February 1994
27th July 1990
26th Dec 1991
12th Nov 1990
19th Dec 1990
27th Dec 1989



Java8 IntSummaryStatistics class to calculate total employees, total age, and average age group of the organization.  


 import java.nio.file.Files;  
 import java.nio.file.Paths;  
 import java.time.LocalDate;  
 import java.util.IntSummaryStatistics;  
 import java.util.stream.Stream;  
 public class DemoExample {  
      public static void main(String... args) {  
           try (Stream<String> lines = Files.lines(Paths.get("demo"))) {  
                IntSummaryStatistics intstream = lines.sequential()  
                          .mapToInt(e -> LocalDate.now().getYear() - Integer.parseInt(e.substring(e.trim().length() - 4)))  
                          .summaryStatistics();  
                long total_age = intstream.getSum();  
                long total_count = intstream.getCount();  
                double avg_age = intstream.getAverage();  
                System.out.println("Total employees :" + total_count);  
                System.out.println("Total age is :" + total_age);  
                System.out.println("Average age is :" + avg_age);  
           } catch (Exception e) {  
                e.printStackTrace();  
           }  
      }  
 }  

Thursday, December 1, 2016

Java with Apache POI

Apache POI to create excel file


Maven dependencies:


<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.9</version>
</dependency>

<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.9</version>
</dependency>

Example:

 import java.io.File;  
 import java.io.FileOutputStream;  
 import java.io.IOException;  
 import java.nio.file.Files;  
 import java.nio.file.Paths;  
 import org.apache.poi.ss.usermodel.Cell;  
 import org.apache.poi.ss.usermodel.Row;  
 import org.apache.poi.ss.usermodel.Sheet;  
 import org.apache.poi.ss.usermodel.Workbook;  
 import org.apache.poi.xssf.usermodel.XSSFWorkbook;  
 public class WorkingWithExcel {  
      public static void main(String[] args) {  
           createWorkBook();  
      }  
      /**  
       * Create workbook with one work sheet. Once work sheet is created, then  
       * content will be added to the work sheet.  
       */  
      private static void createWorkBook() {  
           final String WORKBOOK_NAME = "emp_workbook.xlsx";  
           if (!Files.exists(Paths.get(WORKBOOK_NAME))) {  
                try (FileOutputStream fos = new FileOutputStream(new File("emp_workbook.xlsx"))) {  
                     Workbook workbook = new XSSFWorkbook();  
                     Sheet sheet = workbook.createSheet("emp_details");  
                     int rowcount = 0;  
                     Row row = sheet.createRow(rowcount++);  
                     Object[] colHeading = getColumnHeadings();  
                     int i = 0;  
                     for (Object obj : colHeading) {  
                          Cell cell = row.createCell(i++);  
                          cell.setCellValue((String) obj);  
                     }  
                     Object empData[][] = getEmpData();  
                     for (Object obj[] : empData) {  
                          i = 0;  
                          row = sheet.createRow(rowcount++);  
                          for (Object ob : obj) {  
                               Cell cell = row.createCell(i++);  
                               cell.setCellValue((String) ob);  
                          }  
                     }  
                     workbook.write(fos);  
                     System.out.println("Work book is created successfully with name :" + WORKBOOK_NAME);  
                } catch (IOException e) {  
                     e.printStackTrace();  
                }  
           } else {  
                System.out.println("File already exists with the name :" + WORKBOOK_NAME);  
           }  
      }  
      /**  
       * To return work sheet headings  
       *   
       * @return  
       */  
      private static Object[] getColumnHeadings() {  
           return new Object[] { "EMPNO", "ENAME", "EMAIL", "CITY" };  
      }  
      /**  
       * Actual data to add to work sheet  
       *   
       * @return  
       */  
      public static Object[][] getEmpData() {  
           return new Object[][] { { "SPAN001", "Lakshman", "lakshman.a@spaneos.com", "Bangalore" },  
                     { "SPAN002", "Krish", "krish.t@spaneos.com", "Bangalore" },  
                     { "SPAN003", "Suresh", "suresh.s@spaneos.com", "Bangalore" },  
                     { "SPAN004", "Ramesh", "ramesh.r@spaneos.com", "Bangalore" } };  
      }  
 }  

Thursday, November 17, 2016

Python Programs

Python Programs:

 #Program to print Fibonacci series upto "N". "N" is user input  
 N = int(input("Enter a valid integer : => "))  
 a, b = 0, 1  
 while b <= N:  
   print(b)  
   a, b = b, a + b;  

Friday, April 29, 2016

Selection, Bubble, Insertion Sort in Java

import java.util.Arrays;

public class SortingDemo {
    public static void main(String... args){
            int a[]={2,1,3,5,4,8,7,9,6};
            System.out.println("Before Sorting :"+ Arrays.toString(a));
            insertionSort(a);
            System.out.println("After Sorting :"+ Arrays.toString(a));
    }
    public static void selectionSort(int... arr){
            for(int i=0;i<arr.length-1;i++){
                    for(int j=i+1;j<arr.length;j++){
                        if(arr[i]>arr[j]){
                            int temp=arr[i];
                            arr[i]=arr[j];
                            arr[j]=temp;
                        }

                    }
            }
    }
    public static void bubbleSort(int... a){
            for(int i=0;i<a.length;i++){
                for(int j=0;j<a.length-i-1;j++){
                    if(a[j]>a[j+1]){
                        int temp=a[j];
                        a[j]=a[j+1];
                        a[j+1]=temp;
                    }
                }
            }
    }
    public static void insertionSort(int... arr){
            for(int i=1;i<arr.length;i++){
                int j=i-1;
                int temp=arr[i];
                while(j>=0 && temp<arr[j]){
                    arr[j+1]=arr[j];
                    j--;
                }
                arr[j+1]=temp;
            }
    }
}

Thursday, April 28, 2016

Selection Sort

 #include<stdio.h>  
 #include<conio.h>  
 void showElements(int arr[],int n){  
      int i;  
      if(n==0)  
           printf("[]");  
      else if(n>0)  
           printf("[");  
      for(i=0;i<n;i++){  
           if(i==n-1){  
                printf("%d",arr[i]);  
                printf("]");  
           }else  
                printf("%d,",arr[i]);  
      }  
 }  
 void sortData(int arr[],int n){  
      int i,j,temp;  
      for(i=0;i<n-1;i++){  
           for(j=i+1;j<n;j++){  
                if(arr[i]>arr[j]){  
                  temp=arr[i];  
                  arr[i]=arr[j];  
                  arr[j]=temp;  
                }  
           }  
      }  
 }  
 int getLength(int arr[]){  
      int i=0;  
      while(arr[i]!='\0'){  
        i++;  
      }  
      return i;  
 }  
 void main(){  
      int arr[]={2,1,3,4,9,8,7,6,5};  
      int i,j,len;  
      clrscr();  
      len=getLength(arr);  
      printf("\n Before Sorting Array Elements \n");  
      showElements(arr,len);  
      sortData(arr,len);  
      printf("\n After Sorting Array Elements \n");  
      showElements(arr,len);  
      getch();  
 }  

Friday, April 22, 2016

Floating point error in c - struct

 //Link float error solution  
 #include<stdio.h>  
 #include<conio.h>  
 struct Employee{  
      int empno;  
      char name[50];  
      float salary;  
 };  
 void floatError(float *a){  
      float b=*a;  
      floatError(&b);  
 }  
 void showDetails(struct Employee *emp){  
      printf("\n %d  %s %f",emp->empno,emp->name,emp->salary);  
 }  
 void main(){  
      struct Employee e1;  
      struct Employee e2;  
      clrscr();  
      e1.empno=1001;  
      strcpy(e1.name,"Krishna G");  
      e1.salary=29999.879;  
      e2.empno=1002;  
      strcpy(e2.name,"Nanda Gopal Krishna");  
      e2.salary=59999.987;  
      showDetails(&e1);  
      showDetails(&e2);  
      getch();  
 }  

Stack in C - using array implementation

 //Stack implementation using arrays  
 #include<stdio.h>  
 #include<conio.h>  
 int max=10;  
 int stack[10];  
 int top=-1;  
 int i;  
 void push(int ele){  
   if(top<max){  
      stack[++top]=ele;  
      printf("\n The element is added to stack %d",ele);  
   }else{  
      printf("\n Stack is overflow");  
   }  
 }  
 void pop(){  
      if(top==-1){  
           printf("\n Stack is underflow");  
      }else{  
           printf("\n Element %d is removed ",stack[top]);  
           top--;  
      }  
 }  
 void display(){  
     if(top==-1){  
           printf("\n Stack is empty");  
     }else{  
       printf("[");  
       for(i=0;i<=top;i++){  
           printf(" %d ",stack[i]);  
           if(i<top)  
           printf(",");  
       }  
       printf("]");  
     }  
 }  
 void main(){  
    int ch,ele;  
    int choice=1;  
    clrscr();  
    while(choice){  
       printf("\n1.PUSH 2.POP 3.DISPLAY\n ");  
       scanf("%d",&ch);  
       switch(ch){  
           case 1:printf("\n Enter the element to push \n");  
               scanf("%d",&ele);  
               push(ele);  
               break;  
           case 2:pop();  
               break;  
           case 3:display();  
               break;  
           default: printf("\n Enter valid number (1 to 3)\n");  
       }  
       printf("\n Do you want to continue (yes = 1 no = 0) \n");  
       scanf("%d",&choice);  
    }  
 }  

Monday, March 28, 2016

Reverse String Word by Word in Java ( Character array)

public class ReverseWords {
    public static void main(String[] args) {
        
        String data = "Me loves India";
        System.out.println(data);
        char arr[] = data.toCharArray();
       
        int l = 0;
        for (int i = arr.length - 1; i >= 0; i--) {
            l++;
            
             if (arr[i] == ' ' || i == 0) {
                if (i == 0) {
                    for (int j = i; j < i + l; j++)
                        System.out.print(arr[j]);
                } else {
                    for (int j = i + 1; j < i + l; j++)
                        System.out.print(arr[j]);
                    System.out.print(" ");
                }
                l = 0;
               }
        }

    }
}

Sunday, January 24, 2016

Reverse of the given number using recursion in Java


public int reverse(int num) {
    if (num < 10) {
         return num;
    } else {
          int rev=num%10 * (int) Math.pow(10, (int) Math.log10(num));
          return  rev+ reverse(num / 10);
    }
}

      ------ OR --------


public int reverse(int num) {
   retrun (num < 10)? num:num%10 * (int) Math.pow(10, (int) Math.log10(num))
           +reverse(num / 10);
   }
}

 
   




Thursday, January 21, 2016

Reponse.Redirect with form data in java


//Sending Data Using Get Method

<script type="text/javascript">
 function sendResponseGet(url, extradata, success) {
  var form = $('<form action="' + url + '" method="get">'
    + '<input type="text" name="message" value="' + extradata + '" />'
    + '<input type="text" name="transid" value="' + success + '" />'
    + '</form>');
  form.submit();
 }

// Sending Data Using Post Method

 function sendResponsePost(url, extradata, success) {
  var form = $('<form action="' + url + '" method="post">'
    + '<input type="text" name="message" value="' + extradata + '" />'
    + '<input type="text" name="transid" value="' + success + '" />'
    + '</form>');
  form.submit();
 }
</script>

JSP Code


<button class="btn btn-primary custom-btn"
                    onclick='sendResponseGet("<%=uri%>","
                   <%=message%>","success")'>Send Oxigen Response GET</button>
<hr>
<button class="btn btn-primary custom-btn"
                   onclick='sendResponsePost("<%=uri%>",
                   "<%=message%>","success")'>Send Oxigen Response POST</button>

Spring Boot 3 : JWT with SecurityFilterChain, AuthorizeHttpRequests, RequestMatchers

pom.xml <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0...