Java 8 foreach example program

  • Java 8 introduces for each loop.
  • before that lest see an example of how normal java for each loop.

#1: Java Example program which explain use of for each loop.

  1. package com.instanceofjava.java8;

  2. import java.util.HashMap;
  3. import java.util.Map;

  4. public class ForEachLoop {
  5. /**
  6. * @author www.Instanceofjava.com
  7. * @category interview questions
  8. * Description: java 8 for each loop
  9. *
  10. */
  11. public static void main(String[] args) {
  12. Map<String, Integer> stumarks = new HashMap<>();
  13. stumarks.put("Sai", 65);
  14. stumarks.put("Vamshi", 65);
  15. stumarks.put("Mahendar", 76);
  16. stumarks.put("Muni", 87);
  17. stumarks.put("Manohar", 90);

  18. for (Map.Entry<String, Integer> entry : stumarks.entrySet()) {
  19. System.out.println(entry.getKey() + " marks : " + entry.getValue());
  20. }

  21. }

  22. }

Output:

  1. Muni marks : 87
  2. Vamshi marks : 65
  3. Mahendar marks : 76
  4. Sai marks : 65
  5. Manohar marks : 90

#2: Java Example program which explains the use of for each loop in java 8

  • In the above program we used for each loop to get key value pairs of map.
  • Same thing will be done in java 8 by using stumarks.forEach((k,v)->System.out.println( k + " marks : " + v));

Java 8 java.util.function.Function with example program

  • java.util.function.Function introduced in java 8 for functional programming.
  • Function(T,R) will be used in streams where to take one type of  object and convert to another and return. 
  • And this Function() supports methods like apply(), andThen(), compose() and  identity() etc.
  • Lets see an example on java.util.function.Function.



#1: Java Example program on java.util.function.Function

  1. package com.instanceofjava.java8;

  2. import java.util.function.Function;
  3. /**
  4.  * @author www.Instanceofjava.com
  5.  * @category interview questions
  6.  * 
  7.  * Description: java 8 java.util.function.Function example program
  8.  *
  9.  */
  10. public class Java8Function {

  11. public static void main(String[] args) {
  12. Function<Integer, String> function = (n) -> {
  13. return "Number received: "+n;
  14. };

  15. System.out.println(function.apply(37));
  16. System.out.println(function.apply(64));

  17. }

  18. }

Output:

  1. Number received: 37
  2. Number received: 64

#2: Java example program on Function and explain used of addThen() and compose() methods



java 8 function example

Instance variables in java with example program

  • Variables declared inside a class and outside method without static keyword known as instance variables.
  • Instance variables will be used by objects to store state of the object.
  • Every object will have their own copy of instance variables. where as static variables will be single and shared(accessed) among objects.
  • Instance variables will be associated with the instance(Object)
  • Static variables will be associated with the class.



#1: Java example program on declaring and accessing instance variables.

  1. package com.instanceofjava.instancevariables;

  2. /**
  3.  * @author www.Instanceofjava.com
  4.  * @category interview questions
  5.  * 
  6.  * Description: Instance variables in java with example program
  7.  *
  8.  */
  9. public class InstanceVariables {

  10. String websiteName;
  11. String category;
  12. public static void main(String[] args) {
  13. InstanceVariables obj = new InstanceVariables();
  14. obj.websiteName="www.InstanceOfJava.com";
  15. obj.category="Java tutorial/interview questions";

  16. }

  17. }


  • Instance variables allows all four type of access specifiers in java


instance variables in java with example



  • Instance variables can be final and transient


instance variables in java with example program



  • Instance variables can not be declared as abstract, static strictfp, synchronized and native

Java program to write a string to file using PrintWriter

  • We can write a string to text file in java in various ways.
  • Using PrintWriter we can write or append a string to the text file. 
  • Using println() method of PrintWriter we can save or write string to text file.
  • After completion of using PrintWriter you need to close it by calling close() method.
  • If you are using java 7 , by using try with resources we can implement it and closing will be taken care automatically.
  • Now we will see an example program on how to write or save a string / string variable  to a text file using java 7.

#1: Java Example program to write or save string to file using PrintWriter and java 7 try with resources.

  1. package com.instanceofjava.writetofile;
  2. import java.io.FileNotFoundException;
  3. import java.io.PrintWriter;
  4. /**
  5.  * 
  6.  * @author www.instanceofjava.com 
  7. * @category: java example program
  8.  * 
  9.  * Description: Write a java example program to write string to files using PrintWriter 
  10.  * 
  11. */
  12. public class WriteStringToFile {
  13.  
  14.  public static void main(String[] args) { 
  15.        String str="Write String to file";  
  16.  try(  PrintWriter out = new PrintWriter("data.txt")  )
  17.            
  18. out.println( str );    
  19. catch (FileNotFoundException e) 
  20. {  
  21. e.printStackTrace()
  22.      
  23. }
  24. }   
  25. }

save string to file

Java read file line by line example program

  • Reading a text file line by line in java can be done by using java.io.BufferedReader .
  • Create a BufferedReader class by passing new FileReader(new File("filename")) object to it's constructor.
  • By using readLine() method of  BufferedReader class we can read line by line text from a text file as Strings.
  • Lets see a java example program on hoe to read data from file line by line using BufferedReader class readLine() method.
  • Java read lines from text file example program.


#1: Java Example program to read file line by line

 

  1. package com.instanceofjava.readfile;
  2.  
  3. import java.io.BufferedReader;
  4. import java.io.File;
  5. import java.io.FileReader;
  6. import java.io.IOException;
  7. /** *  * 
  8. @author www.instanceofjava.com 
  9. * @category: Interview Programs 
  10. * @description: How to read text file line by line in java example program 
  11. * */
  12.  
  13. public class ReadFile {
  14.  
  15.     public static void main(String[] args) {        
  16.         
  17.         try {            
  18.            File fileName = new File("E:\\data.txt");
  19.             FileReader fileReader = new FileReader(fileName);     
  20.             BufferedReader bufferedreader = new BufferedReader(fileReader);           
  21.             StringBuffer sb = new StringBuffer();
  22.             String strLine;            
  23.            while ((strLine = bufferedreader.readLine()) != null) {
  24.                 sb.append(strLine);
  25.                 sb.append("\n");        
  26.             }         
  27.            fileReader.close();
  28.            System.out.println(sb.toString()); 
  29.          } catch (IOException e) {
  30.             e.printStackTrace();     
  31.    }
  32.  
  33.     }
  34.  
  35. }

Output:

  1. java read file line by line example
  2. java read file line by line java 8
  3. java read lines from text file 
  4. example bufferedreader java example

#2: Java example program to read text file line by line using java 7 try with resource example



read file line by line java


#3: Java example program to read text file line by line using java 8 example (Using stream)

  1. package com.instanceofjava.readfile;
  2. import java.io.IOException;
  3. import java.nio.file.Files;
  4. import java.nio.file.Paths;
  5. import java.util.stream.Stream;
  6. /**
  7.  *
  8. * @author www.instanceofjava.com
  9.  * @category: Interview Programs 
  10. * @description: How to read text file line by line in java example program using java 8 stream
  11. */
  12. public class ReadFile {
  13. public static void main(String[] args) throws IOException {
  14.  
  15. try (Stream<String> stream = Files.lines(Paths.get("E:\\data.txt"))) 
  16. {           
  17.  
  18.  stream.forEach(System.out::println);
  19.  
  20. }
  21. }
  22. }

Convert to maven project in eclipse java

  • In order to convert any java project in to maven using eclipse we need to install m2e plugin.
  • Latest versions of eclipse are coming with this m2e plugin by default.
  • If not found this plugin we can install it by help->install->click on add and enter http://download.eclipse.org/technology/m2e/releases. 
  • currently i am using eclipse oxygen version so it is having m2e plugin.
  • I have created a normal java project and i want to convert that into a maven project.
  • To convert any project in to maven right click on the project and ->configure->convert to maven project. 
  • After that a window will be opened and you need to enter group id and artifact id and then click on finish.  
  • convert to maven project eclipse luna / convert to maven project is not visible in eclipse /convert to maven project option not available in eclipse.



Right click on project and select configure-> convert to maven project.


convert to maven project java

Project will be converted to maven by creating pom.xml file.

how to convert to maven project java

 

pom.xml

  1. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.or
  2. /2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
  3. http://maven.apache.org/xsd/maven-4.0.0.xsd">
  4.   <modelVersion>4.0.0</modelVersion>
  5.   <groupId>com.instanceofjava.maven</groupId>
  6.   <artifactId>MavenProject</artifactId>
  7.   <version>0.0.1-SNAPSHOT</version>
  8.   <build>
  9.     <sourceDirectory>src</sourceDirectory>
  10.     <plugins>
  11.       <plugin>
  12.         <artifactId>maven-compiler-plugin</artifactId>
  13.         <version>3.7.0</version>
  14.         <configuration>
  15.           <source>1.8</source>
  16.           <target>1.8</target>
  17.         </configuration>
  18.       </plugin>
  19.     </plugins>
  20.   </build>
  21. </project>

Add dependencies to your pom.xml file

  1.  <properties>
  2.         <springVersion>5.0.3.RELEASE</springVersion>
  3.       </properties>
  4.       <dependencies>
  5.         <dependency>
  6.           <groupId>org.springframework</groupId>
  7.           <artifactId>spring-context</artifactId>
  8.           <version>${springVersion}</version>
  9.         </dependency>
  10.        <dependency>
  11.          <groupId>org.springframework</groupId>
  12.          <artifactId>spring-core</artifactId>
  13.           <version>5.0.3.RELEASE</version>
  14.         </dependency>
  15.       </dependencies>

How to read values from properties file in java example

  • To store configurable parameters, .properties file will be used in java.
  • We can Store data in key value pair (key=value).
  • Re compilation not required if we change any keys or values in properties file.
  • Used for internationalization  and to store frequently changeable values. 
  • java.util.Properties class is sub class of Hashtable. 
  • We can read / load the propertied file using InputStream.
  • InputStream inputStream = getClass().getClassLoader().getResourceAsStream(properties_FileName);
  • Create a maven project, under resources create one .properties file and load this file in main class using getClass().getClassLoader().getResourceAsStream(properties_FileName).
  • Lets see an example java program on java read properties file from resource folder or how to read values from properties file in java example or how to get values from properties file in java.

 #1: Create a maven project:

java read properties file from classpath


Create properties file:

reading properties file in java

#1: Java example program  to get values from properties file in java

  1. package com.instanceofjava.propertiesfile;
  2. import java.io.FileNotFoundException;
  3. import java.io.IOException;
  4. import java.io.InputStream;
  5. import java.util.Date;
  6. import java.util.Properties;
  7. /**
  8.  *  
  9. * @author www.instanceofjava.com
  10.  * @category: java example programs
  11.  *  
  12. * Write a java example program to read/ load properties file
  13.  *
  14.  */
  15. public class ReadPropertiesFile {
  16.  
  17.     public Properties getProperties() throws IOException {
  18.         
  19.         InputStream inputStream=null;
  20.         Properties properties = new Properties();
  21.         try {
  22.             
  23.             String propFileName = "config.properties";
  24.  
  25.             inputStream = getClass().getClassLoader().getResourceAsStream(propFileName);
  26.  
  27.             if (inputStream != null) {
  28.                 properties.load(inputStream);
  29.             } else {
  30.                 throw new FileNotFoundException("property file '" + propFileName + "' not found
  31. in the classpath");
  32.             }
  33.  
  34.  
  35.         } catch (Exception e) {
  36.             System.out.println("Exception: " + e);
  37.        } finally {
  38.             inputStream.close();
  39.         }
  40.          return properties;
  41.     }
  42.     
  43.     
  44.     public static void main(String[] args) throws IOException {
  45.         
  46.         ReadPropertiesFile obj= new ReadPropertiesFile();
  47.         Properties properties=obj.getProperties();
  48.         // get the each property value using getProperty() method 
  49.         System.out.println("username: "+properties.getProperty("username"));
  50.         System.out.println("password: "+properties.getProperty("password"));
  51.         System.out.println("url: "+properties.getProperty("url"));
  52.         
  53.                 
  54.     }
  55.  
  56. }

Output:

  1. username: user1
  2. password: abc123
  3. url: www.instanceofjava.com
Select Menu