Showing posts with label corejava. Show all posts
Showing posts with label corejava. Show all posts

Saturday, June 18, 2016

Java 8 : Lambda Expression : Refactoring from external to internal iterator

Lambda Expression in Java 8

In this example , Refactoring from external to internal iterator by simple examples with printing values.


In order to write java code to  print array elements. in  previous versions of java.
lot of code need to write for an iterations. For example :


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
import java.util.Arrays;
import java.util.List;

public class TestLamda {
 public static void main(String[] args) {
  List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
  for (int i = 0; i < numbers.size(); i++) {
   System.out.println("Numbers:" + numbers.get(i));

  }
 }
}

Output:











We can may simplify the above code by using forEach Loop:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
import java.util.Arrays;
import java.util.List;

public class TestLamda {
 public static void main(String[] args) {
  List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
  /*for (int i = 0; i < numbers.size(); i++) {
   System.out.println("Numbers:" + numbers.get(i));
  }*/
  for(int j : numbers){
   System.out.println(j);
  }
 }
}
Output:










The above 2 Ways are we called in Java External Iterator.

Java Divided iterators based on who controls the iterations process?
A fundamental task is deciding which party controls the iteration. the iterator or the client that uses the iterator. 
External Iterator:
When the client controls the iteration, the iterator is called an external iterator (Example: C++ and Java).
Internal Iterator :
when the iterator controls it, the iterator is an internal iterator (Example : Lisp and functional languages)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;

public class TestLamda {
 public static void main(String[] args) {
  List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
  /*
   * for (int i = 0; i < numbers.size(); i++) {
   * System.out.println("Numbers:" + numbers.get(i)); }
   */
  /*
   * for(int j : numbers){ System.out.println(j); }
   */
  numbers.forEach(new Consumer<Integer>() {
   @Override
   public void accept(Integer value) {
    System.out.println(value);
   }
  });
 }
}
Output:











The above one is better way to do the iteration at run time polymorphism.
But we are created unanimous inner class.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;

/**
 * @author nareshn
 *
 */
public class TestLamda {
 public static void main(String[] args) {
  List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
  /*
   * for (int i = 0; i < numbers.size(); i++) {
   * System.out.println("Numbers:" + numbers.get(i)); }
   */
  /*
   * for(int j : numbers){ System.out.println(j); }
   */
  /*
   * numbers.forEach(new Consumer<Integer>() {
   * 
   * @Override public void accept(Integer value) {
   * System.out.println(value); } });
   */
  numbers.forEach((Integer value) -> System.out.println(value));
 }

}
Output:











This one is called a simple Lambda function in it.
A Function should contains 4 parts: 1.Body , 2.Name, 3.Parameter List,  4.Return Type.

Here rather than accepting single abstract method , interface , now forEach method is more than willing to accept Lambda expression

In Java 1.0 , Thread Class rather than sending a new Runnable , now we can send a Lambda expression. it is very good move.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;

/**
 * @author nareshn
 *
 */
public class TestLamda {
 public static void main(String[] args) {
  List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
  /*
   * for (int i = 0; i < numbers.size(); i++) {
   * System.out.println("Numbers:" + numbers.get(i)); }
   */
  /*
   * for(int j : numbers){ System.out.println(j); }
   */
  /*
   * numbers.forEach(new Consumer<Integer>() {
   * 
   * @Override public void accept(Integer value) {
   * System.out.println(value); } });
   */
  /*numbers.forEach((Integer value) -> System.out.println(value));*/
  //no need to mention return type
  numbers.forEach(value -> System.out.println(value));
 }
}
Output:











Here we no need to mention return type.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;

/**
 * @author nareshn
 *
 */
public class TestLamda {
 public static void main(String[] args) {
  List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
  /*
   * for (int i = 0; i < numbers.size(); i++) {
   * System.out.println("Numbers:" + numbers.get(i)); }
   */
  /*
   * for(int j : numbers){ System.out.println(j); }
   */
  /*
   * numbers.forEach(new Consumer<Integer>() {
   * 
   * @Override public void accept(Integer value) {
   * System.out.println(value); } });
   */
  /* numbers.forEach((Integer value) -> System.out.println(value)); */
  // no need to mention return type
  /* numbers.forEach(value -> System.out.println(value)); */
  // perform some operations multiply, addition,substact or more for given
  // array values.
  numbers.forEach(value -> System.out.println(value * 2));
 }
}
Output:













Here we can not only a value, some mathematical operations to the array elements.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;

/**
 * @author nareshn
 *
 */
public class TestLamda {
 public static void main(String[] args) {
  List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
  /*
   * for (int i = 0; i < numbers.size(); i++) {
   * System.out.println("Numbers:" + numbers.get(i)); }
   */
  /*
   * for(int j : numbers){ System.out.println(j); }
   */
  /*
   * numbers.forEach(new Consumer<Integer>() {
   * 
   * @Override public void accept(Integer value) {
   * System.out.println(value); } });
   */
  /* numbers.forEach((Integer value) -> System.out.println(value)); */
  // no need to mention return type
  /* numbers.forEach(value -> System.out.println(value)); */
  // perform some operations multiply, addition,substact or more
  // for given
  // array values.
  /* numbers.forEach(value -> System.out.println(value * 2)); */

  // if we print direct value
  numbers.forEach(System.out::println);
 }
}
Output:

Wednesday, February 11, 2015

Applet Java code Database Connection display one table

DatabaseApplet.java



package abc;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.*;


import javax.swing.*;


public class Ab extends JApplet implements ActionListener
{
 static final long serialVersionUID = 1L;
 private JButton bttnForLogIn, bttnForTime,bttnForViewingTables;
 private String server_connect,user_name,user_pwd,oracle_driver;
 private Connection conn;
 private PreparedStatement pstmt;
 private ResultSet rs;
 
 

 private boolean getConnected=true;
 private JLabel lblTitle, lblDisplayTime; 
 private JTextArea textArea;
 public void init() {
  // TODO Auto-generated method stub

  setSize(800, 700);
  if(getConnected){
   setLayout(new BorderLayout());}

  add(new Ab(),BorderLayout.CENTER);



  System.out.println("Init");

 }


 public Ab()
 {
  if(getConnected){

   lblTitle = new JLabel("Oracle Database Table Data");
   lblTitle.setFont(new Font("Slab Serif", Font.BOLD, 18));
   lblTitle.setForeground(Color.red);
   lblTitle.setBounds(100, 11, 400, 60);

   oracle_driver = "oracle.jdbc.driver.OracleDriver";
   getConnected = true;
   JScrollPane scrollPane;
   getContentPane().add(scrollPane = new JScrollPane(this.textArea = new JTextArea()));
   textArea.setEditable(false);
   textArea.setBackground(Color.WHITE);
   scrollPane.setBounds(40,200, 200, 100);

   getContentPane().setBackground(Color.WHITE);
   bttnForLogIn = new JButton("Log In");
   bttnForLogIn.setBounds(21, 70, 150, 20);
   bttnForLogIn.addActionListener(this);





   bttnForTime = new JButton("Table:");
   bttnForTime.setBounds(51, 110, 150, 20);

   bttnForTime.addActionListener(this);


   lblDisplayTime = new JLabel("");
   lblDisplayTime.setFont(new Font("Times New Roman",30,12));
   lblDisplayTime.setForeground(Color.RED);
   lblDisplayTime.setBounds(180, 345, 400, 50);



   getContentPane().add(lblTitle);

   getContentPane().add(bttnForLogIn);  

   getContentPane().add(bttnForTime);
   //getContentPane().add(bttnForViewingTables);

   getContentPane().add(lblDisplayTime);


  }
 }

 public void setConnection(boolean getConnection)
 {
  getConnection=false;
 }

 public void buttonChanged(){

  bttnForLogIn.setText("Log Out");
 }
//main connection
 public void actionPerformed(ActionEvent e)
 {
  if(e.getSource() == bttnForLogIn)
  {
   user_name = "system";
   user_pwd = "manager";
   server_connect = "jdbc:oracle:thin:@localhost:1521:XE";
   if(getConnected)
   {
    if(testConnection() == 0)
    {

     JOptionPane.showMessageDialog(null, "Successful Completion");

     bttnForTime.setEnabled(true);

     buttonChanged();
     getConnected = false;
    } else
    {
     JOptionPane.showMessageDialog(null, "Oracle DB connection fail");
     bttnForTime.setEnabled(false);


    }
   } else 
   {
    try
    {
     conn.close();
    }
    catch(SQLException e1)
    {
     e1.printStackTrace();
    }
    bttnForLogIn.setText("Login");
    setConnection(getConnected);

    JOptionPane.showMessageDialog(null, "You have logged out! Have a good day!");
    
    
   }
  }else
   if(e.getSource() == bttnForTime)
    Table1();


   else {
    if(e.getSource() == bttnForViewingTables){

     Table1();
          
    }}




 }
 


 

 public int testConnection()
 {
  int flag = 0;
  try
  {
   Class.forName(oracle_driver);
  }
  catch(Exception e)
  {
   JOptionPane.showMessageDialog(null, e.getMessage());
  }
  try
  {
   conn = DriverManager.getConnection(server_connect, user_name, user_pwd);
  }
  catch(SQLException e)
  {
   JOptionPane.showMessageDialog(null, e.getMessage());
   flag = -1;
  }
  return flag;
 }
 

 private void Table1()  
 {
  try  
  {
   String stmtQuery = "select * from user_details";
   pstmt = conn.prepareStatement(stmtQuery);
   rs = pstmt.executeQuery();
   while(rs.next())
   {
    
    id=rs.getString(1);
     name = rs.getString(2);
     
     textArea.append("|"+id+" | "+name+"|"+"\n");
    // textArea.append("");
    
    System.out.println(name);
    
   }
   
   rs.close();
   pstmt.close();
  } catch(SQLException e2)
  {
   e2.printStackTrace();
  }
  
  
 }
 static String id;
 static String name;


 @Override
 public void destroy() {
  // TODO Auto-generated method stub
  System.out.println("destroy");
 }

 @Override
 public void start() {
  // TODO Auto-generated method stub
  System.out.println("Start");
 }

 @Override
 public void stop() {
  // TODO Auto-generated method stub
  if(!getConnected)
   System.out.println("Stop");

 }

} 

Run and execute ; change ur Oracle URL,Username, Password, Tablename