スキップしてメイン コンテンツに移動

投稿

ラベル(Java8)が付いた投稿を表示しています

Java 8 Lamnda: Print All Elements in Collection

When you write a program, I think sometimes you would like to prontall elements in collection for debugging purpose. Before Jva 7 we need to wrote small code snippet for iterating collection and printing out its element. However in Java 8 you can write this kind of code quite quickly. Here is an example for printing out all system properties. System.getProperties().entrySet().stream().forEach(System.out::println); I think the advantedge of this code is readability and writability - You can read or write code just from left to right :D

Java 8 Lambda : Comparator

Java 8 makes your code much more readble and simpler. In this post, I will show you Comparator example. Beofre Java 8 I always had to write and put utility comparator for String in my program. Annoying... package com.dukesoftware.utils.common; import java.util.Comparator; public enum StringComparator implements Comparator<String> { Instance; public int compare(String o1, String o2) { if(o1 == nul){ if(o2 == null) return 0; return -1; } return o1.compareTo(o2); } } Of course you can use Java Commons library, but it is too much to add jar to buildpath only for small code snippet. Java 8 Lambda Expression See this code! Quite short! Comparator.nullsFirst(Comparator.comparing(String::toString));

Java 8 Lambda Expression

I am very excited about new Java 8 features, especially lambda expression. I am jealous that C# had lambda expression when it was introduced in C# 3.0 loooong time ago. Let me show you a power of lambda expression by simple code example - FileFiter. Why I choose this example? Well, I have been so frustrated that I always had to write a bit redundant code even if for very simple FileFilter. Please see following example code. Hope the example attracts you... package com.dukesoftware.io; import java.io.File; import java.io.FileFilter; public class FileFilters { // legacy file filter - no lambda expression public static final FileFilter DIRECTORY_FILTER_BEFORE_JAVA8_NO_LAMBDA = new FileFilter() { @Override public boolean accept(File pathname) { return pathname.isDirectory(); } }; // basic lambda expression introduced since java 8 public static final FileFilter DIRECTORY_FILTER_JAVA8_LAMBDA_FIRST = (File pathname) -&g