Last active
August 29, 2015 14:11
-
-
Save madhub/a86a4da7eb664236f726 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* To change this license header, choose License Headers in Project Properties. | |
* To change this template file, choose Tools | Templates | |
* and open the template in the editor. | |
*/ | |
package demo; | |
import java.awt.event.ActionEvent; | |
import java.awt.event.ActionListener; | |
import java.io.IOException; | |
import java.nio.file.Files; | |
import java.nio.file.Path; | |
import java.nio.file.Paths; | |
import java.util.Arrays; | |
import java.util.Collections; | |
import java.util.Comparator; | |
import java.util.LinkedList; | |
import java.util.List; | |
import java.util.Random; | |
import java.util.stream.Collectors; | |
import java.util.stream.Stream; | |
/** | |
* | |
* @author madhub | |
*/ | |
public class Java7to8Demo { | |
public static void main(String[] args) { | |
} | |
/** | |
* Lambda expression for Action listener interface | |
*/ | |
public static void sample1() { | |
// Java 7 | |
ActionListener al = new ActionListener() { | |
@Override | |
public void actionPerformed(ActionEvent e) { | |
System.out.println(e.getActionCommand()); | |
} | |
}; | |
// Java 8 | |
ActionListener al8 = e -> System.out.println(e.getActionCommand()); | |
} | |
/** | |
* demonstrate lambda expression for iterating over collection | |
*/ | |
public static void iterationOverCollectionSample() { | |
List<String> names = Arrays.asList("Rachel Green", "Monica Geller", "Phoebe Buffay", "Joey Tribbiani", | |
" Chandler Bing", " Ross Geller "); | |
// Java 7 | |
for (String string : names) { | |
System.out.println(string); | |
} | |
// Java 8 | |
// on any collection , you can use foreach | |
names.forEach(value -> System.out.println(value)); | |
// or | |
names.forEach(System.out::println); | |
} | |
/** | |
* demonstrate lambda expression for sorting elements inside collection | |
*/ | |
public static void sortSample() { | |
List<String> names = Arrays.asList("Rachel Green", "Monica Geller", "Phoebe Buffay", "Joey Tribbiani", | |
" Chandler Bing", " Ross Geller "); | |
// Java 7 | |
Collections.sort(names, new Comparator<String>() { | |
@Override | |
public int compare(String s1, String s2) { | |
return s1.length() - s2.length(); | |
} | |
}); | |
// Java 8 | |
Collections.sort(names, (s1, s2) -> s1.length() - s2.length()); | |
// or | |
names.sort((s1, s2) -> s1.length() - s2.length()); | |
} | |
/** | |
* demonstrate lambda expression for find max or min value in collection | |
*/ | |
public static void findMax() { | |
List<Double> list = Arrays.asList(2.0, 3.5, 1.0, 5.6); | |
// Java 7 | |
double max = 0; | |
for (Double d : list) { | |
if (d > max) { | |
max = d; | |
} | |
} | |
//Java 8 | |
max = list.stream().reduce(0.0, Math::max); | |
// or | |
max = list.stream().mapToDouble(Number::doubleValue).max().getAsDouble(); | |
} | |
/** | |
* demonstrate lambda expression for finding average value in collection | |
*/ | |
public static void findCalculateAverage() { | |
List<Double> list = Arrays.asList(2.0, 3.5, 1.0, 5.6); | |
// Java 7 | |
double total = 0; | |
double ave = 0; | |
for (Double d : list) { | |
total +=d; | |
} | |
ave = total /((double)list.size()); | |
//Java 8 | |
ave = list.stream().mapToDouble(Number::doubleValue).average().getAsDouble(); | |
} | |
/** | |
* demonstrate lambda expression joining string value | |
*/ | |
public static void stringJoining() { | |
// Employee entity class | |
class Employee { | |
private String name; | |
private int age; | |
public Employee(String name, int age) { | |
this.name = name; | |
this.age = age; | |
} | |
public String getName() { | |
return name; | |
} | |
public int getAge() { | |
return age; | |
} | |
} | |
List<Employee> employees = Arrays.asList( new Employee("Chandler", 35), new Employee("Joe", 29)); | |
// Java 7 | |
List<String> names = new LinkedList<>(); | |
for (Employee emp : employees) | |
names.add(emp.getName()); | |
String.join(",", names); | |
// Java 8 | |
String collect = employees.stream().map(Employee::getName).collect(Collectors.joining()); | |
} | |
/** | |
* demonstrate lambda expression joining string value with prefix,suffix and delimiter | |
*/ | |
public static void stringJoiningWithPrefixSuffix() { | |
List<String> names = Arrays.asList("Rachel Green", "Monica Geller", "Phoebe Buffay", "Joey Tribbiani", | |
" Chandler Bing", " Ross Geller "); | |
// Java 7 | |
int index = 0; | |
StringBuilder builder = new StringBuilder(); | |
builder.append("{"); | |
for (String name : names) { | |
if ( index < (names.size() - 1)){ | |
builder.append(name+","); | |
} | |
index++; | |
} | |
builder.append("}"); | |
// Java 8 | |
String collect = names.stream().collect(Collectors.joining("," ,"{", "}")); | |
} | |
/** | |
* list all lines of using stream & lambda function | |
* @throws IOException | |
*/ | |
public static void listAllLinesOfGivenFile() throws IOException { | |
try (Stream st = Files.lines(Paths.get("c:\\temp\\sample.log"))) { | |
st.forEach(System.out::println); | |
} | |
} | |
/** | |
* usage of stream & lambda expression to generate 5 random numbers | |
* @throws IOException | |
*/ | |
public static void randomNumberSample() throws IOException { | |
Stream<Double> generate = Stream.generate(() -> Math.random()); | |
generate.limit(5) // limit 5 | |
.forEach(System.out::println); // iterate over stream | |
Files.list(Paths.get(".")).forEach(System.out::println); | |
} | |
/** | |
* The limit(int n) method can be used to limit a stream to the given number of elements | |
*/ | |
public static void randomNumberSample2() { | |
Random rnd = new Random(); | |
rnd.ints().limit(10) | |
.forEach(System.out::println); | |
} | |
/** | |
* List alphabetically sorted first 5 java files in the current directory | |
* @throws IOException | |
*/ | |
public static void listFiles() throws IOException { | |
Files.list(Paths.get(".")) | |
//.map(Path::getFileName) // still a path | |
.map(Path::toString) // convert to Strings | |
.filter(name -> name.endsWith(".java")) | |
.sorted() // sort them alphabetically | |
.limit(5) // first 5 | |
.forEach(System.out::println); | |
} | |
/** | |
* calculates the average length of non-empty lines in the file “Nio.java”. | |
* Demonstrates, map, filter & reduce | |
* @throws IOException | |
*/ | |
public static void calculateAverageLengthOfLine() throws IOException { | |
System.out.println("\n----->Average line length:"); | |
System.out.println( | |
Files.lines(Paths.get("Nio.java")) | |
.map(String::trim) // map | |
.filter(s -> !s.isEmpty()) // filter | |
.collect(Collectors.averagingInt(String::length)) // reduce | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment