Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
This class will run a few simple tests using the new Java 8 features 'lambda expressions' and 'Streams'.
import java.util.Arrays;
import java.util.List;
import java.util.ArrayList;
import java.util.stream.*;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.File;
public class JavaEightTests
{
public static void main(String[] args) throws Exception
{
System.out.println("Welcome to Java 8");
JavaEightTests jet = new JavaEightTests();
List<String> words = JavaEightTests.getLinuxWords();
jet.test1();
jet.processStream(words.stream());
jet.processStream(words.stream());
jet.processStream(words.parallelStream());
jet.processStream(words.parallelStream());
}
public void processStream(Stream<String> wordStream) throws Exception
{
Long start = System.currentTimeMillis();
List<String> beginsWithTBothCase = wordStream
.map(s -> {
for(int i = 0; i < 100; i++)
{
s = s.toLowerCase().toUpperCase();
}
return s;
})
.collect(Collectors.toList());
long totalTime = System.currentTimeMillis() - start;
System.out.println(String.format("Task took %.3f seconds to execute.", totalTime/1000f));
}
public void test1()
{
List<String> strings = Arrays.asList("One","Two","Three","Four","Five");
List<String> longerThanThree = strings
.stream()
.filter(s -> s.length() > 3)
.collect(Collectors.toList());
List<String> uppers = strings
.stream()
.map(s -> s.toUpperCase())
.collect(Collectors.toList());
List<String> beginsWithTBothCase = strings
.stream()
.filter(s -> s.startsWith("T"))
.map(s -> s.toLowerCase() + s.toUpperCase())
.collect(Collectors.toList());
System.out.println(strings);
System.out.println(longerThanThree);
System.out.println(uppers);
System.out.println(beginsWithTBothCase);
}
public static List<String> getLinuxWords() throws Exception
{
BufferedReader br = new BufferedReader(new FileReader(new File("linux.words")));
List<String> linuxWords = new ArrayList<String>();
String line = br.readLine();
while(line != null)
{
linuxWords.add(line);
line = br.readLine();
}
return linuxWords;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment