Filter collection elements thus only elements with less than 4 characters are returned using Java 7 Vs Java 8

Filter collection elements thus only elements with less than 4 characters are returned :

import static java.util.stream.Collectors.toList;

import java.util.ArrayList;
import java.util.List;

public class Test {

	/**
	 * Filter elements with less than 4 characters in a Collection to upper case
	 * using Java 7
	 *
	 * @param inList
	 * @return
	 */
	public static List<String> filter7(List<String> inList) {
		List<String> list = new ArrayList<>();
		for (String str : inList) {
			if (str.length() < 4) {
				list.add(str);
			}
		}
		return list;
	}

	/**
	 * Filter elements with less than 4 characters in a Collection to upper case
	 * using Java 8
	 *
	 * @param inList
	 * @return
	 */
	public static List<String> filter8(List<String> inList) {
		return inList.stream() // Convert collection to Stream
				.filter(value -> value.length() < 4) // Filter elements with length smaller than 4 characters
				.collect(toList()); // Collect results to a new list
	}

	public static void main(String[] args) {
		List<String> inList = new ArrayList<>();
		inList.add("Tuturself");
		inList.add("c"); // This will be part of output
		inList.add("pl/sql");
		inList.add("c++");// This will be part of output
		System.out.println("Input List >> " + inList);
		System.out.println("Filter by Java 7 >> " + filter7(inList));
		System.out.println("Filter by Java 8 >> " + filter8(inList));
	}
}

The output is

Input List >> [Tuturself, c, pl/sql, c++]
Filter by Java 7 >> [c, c++]
Filter by Java 8 >> [c, c++]

 

Java-8 12 Stream 12

FOLLOW US ON LinkedIn



Explore Tutu'rself