JDK1.8 Stream

1.Streams filter() and collect() 進行過濾數據和收集數據

按照正常的方式過濾數據   java

ist<String> lines = Arrays.asList("spring", "node", "mkyong");
List<String> result = getFilterOutput(lines, "mkyong");
for (String temp : result) {
	System.out.println(temp);	//output : spring node
}

    //...
    private static List<String> getFilterOutput(List<String> lines, String filter) {
        List<String> result = new ArrayList<>();
        for (String line : lines) {
            if (!"mkyong".equals(line)) {
                result.add(line);
            }
        }
        return result;
    }

JDK1.8以後過濾數據的方式 node

import java.util.stream.Collectors;

//...
                List<String> lines = Arrays.asList("spring", "node", "mkyong");

		List<String> result = lines.stream() 			//convert list to stream
			.filter(line -> !"mkyong". equals (line))	//filters the line, equals to "mkyong"
			.collect(Collectors.toList());			//collect the output and convert streams to a List

		result.forEach(System.out::println);			//output : spring node        

 

2. Streams filter(), findAny() and orElse()
按照正常方式,經過名字獲取對象
ist<Person> persons = Arrays.asList(new Person("mkyong"),
	new Person("michael"), new Person("lawrence"));

Person result = getStudentByName(persons, "michael");

//...
    private Person getStudentByName(List<Person> persons, String name) {

        Person result = null;
        for (Person temp : persons) {
            if (name.equals(temp.getName())) {
                result = temp;
            }
        }
        return result;
    }

使用stream.filter ()過濾一列表,並.findAny().orElse (null)返回一個對象的條件。spring

List<Person> persons = Arrays.asList(new Person("mkyong"),
		new Person("michael"), new Person("lawrence"));

Person result = persons.stream()				   // Convert to steam
	.filter(x -> "michael".equals(x.getName()))	// we want "michael" only
	.findAny()									// If 'findAny' then return found
	.orElse(null);								// If not found, return null  

更多賽選條件this

List<Person> persons = Arrays.asList(new Person("mkyong", 20),
	    new Person("michael", 21), new Person("lawrence", 23));

	Person result = persons.stream()
	    .filter((x) -> "michael".equals(x.getName()) && 21==x.getAge())
	    .findAny()
	    .orElse(null);

	//or like this
	Person result = persons.stream()
	    .filter(x -> {
	        if("michael".equals(x.getName()) && 21==x.getAge()){
	            return true;
	        }
	        return false;
	    }).findAny()
	    .orElse(null);

 使用filter和map例子spa

List<Person> persons = Arrays.asList(new Person("mkyong", 20),
	new Person("michael", 21), new Person("lawrence", 23));

String name = persons.stream()
	.filter(x -> "michael".equals(x.getName()))
	.map(Person::getName)						//convert stream to String
	.findAny()
	.orElse("");

//name = michael
相關文章
相關標籤/搜索