创建自定义流

时间:2017-09-20 11:33:06

标签: java java-8 java-stream

我可以在Stream<String>中加载数据。 我正在使用Stream,因为我无法将所有数据加载到内存中,因此不允许收集。 我想构建一个Stream<MyClass>来对MyClass的对象执行某些操作,并使用Stream<String>提供流。

2 个答案:

答案 0 :(得分:3)

鉴于您已经拥有Stream<String>,并假设其中有MyClass(String)构造函数,请写下:

Stream<MyClass> stream = stringStream.map(MyClass::new);

答案 1 :(得分:-2)

Java示例:不使用Stream过滤集合

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


class Book{

    int book_id;
    String book_name;
    float price;

    public Book() {

    }

    public Book(int book_id, String book_name, float price) {
        this.book_id = book_id;
        this.book_name = book_name;
        this.price = price;
    }
}

public class Mystringstream {

    public static void main(String[] args) {
     List<Book> booklist= new ArrayList<Book>();
     booklist.add(new Book(101,"java",500.25f));
     booklist.add(new Book(102,"php",300.20f));
     booklist.add(new Book(103,"c",400.34f));

     List<Float> bookpricelist=new ArrayList<Float>();
     for(Book book:booklist){
         if(book.price<500){
             bookpricelist.add(book.price);

         }
     }
        System.out.println("Filter Book Price List: "+bookpricelist);
    }
}

<强>输出:

过滤书价格表:[300.2,400.34]

Java Stream示例:使用Stream过滤集合

import java.util.ArrayList;

import java.util.List;

import java.util.stream.Collectors;


class Book{
    int book_id;
    String book_name;
    float price;

    public Book() {

    }

    public Book(int book_id, String book_name, float price) {
        this.book_id = book_id;
        this.book_name = book_name;
        this.price = price;
    }
}

public class Mystringstream {

    public static void main(String[] args) {

     List<Book> booklist= new ArrayList<Book>();
     booklist.add(new Book(101,"java",500.25f));
     booklist.add(new Book(102,"php",300.20f));
     booklist.add(new Book(103,"c",400.34f));

     List<Float> bookpricelist=booklist.stream().filter(p->p.price < 500).map(p->p.price).collect(Collectors.toList());

        System.out.println("Filter Book Price List: "+bookpricelist);

    }
}

输出 过滤书价格表:[300.2,400.34]