欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

JDK1.8 Stream

程序员文章站 2022-06-04 19:30:06
...
1.Streams filter() and collect() 进行过滤数据和收集数据

按照正常的方式过滤数据   

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之后过滤数据的方式 

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)返回一个对象的条件。

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  

更多赛选条件

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例子

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