Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/331.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 8流:类型不匹配无法将流对象转换为列表对象_Java_Java Stream - Fatal编程技术网

Java 8流:类型不匹配无法将流对象转换为列表对象

Java 8流:类型不匹配无法将流对象转换为列表对象,java,java-stream,Java,Java Stream,大家好,我想问一下,为什么要将一个结果集从stream分配给一个变量,我做得对吗?我是这样做的,但有一些错误 public class MainApp { public static void main(String[] args) { List<Person> customers = new ArrayList<>(); customers.add(new Person(1, "test", "test", 25)); customers.a

大家好,我想问一下,为什么要将一个结果集从stream分配给一个变量,我做得对吗?我是这样做的,但有一些错误

public class MainApp {

public static void main(String[] args) {

    List<Person> customers = new ArrayList<>();
    customers.add(new Person(1, "test", "test", 25));
    customers.add(new Person(2, "test1", "test2", 3));
    customers.add(new Person(3, "test2", "test3", 62));

    List<Person> sList = customers.stream()
                                  .sorted();


}


}
public类MainApp{
公共静态void main(字符串[]args){
列出客户=新建ArrayList();
添加(新人员(1,“测试”,“测试”,25));
添加(新的人(2,“test1”,“test2”,3));
添加(新的人(3,“test2”,“test3”,62));
List sList=customers.stream()
.sorted();
}
}
我得到了这个错误:

"type mismatch cannot convert stream<Person> to list<Person>"
“类型不匹配无法将流转换为列表”

您必须从

List<Person> sList = customers.stream().sorted();
List sList=customers.stream().sorted();

List sList=customers.stream().sorted().collect(collector.toList());

sorted
返回流实例,进一步允许执行其他操作,如筛选。因此,根据streams API,如果您希望获取列表实例,应该通过调用
collect
方法来实现。

如果您试图对列表进行排序,只需使用
list.sort()
。流的用途是什么?
排序
是一个中间操作,后面还有一个流。如果你想从流中创建一个
列表
,你需要收集。谢谢你的回复,先生,解决了错误,但是当我尝试运行时,这个错误会显示“不知道为什么?”?“线程“main”中的异常java.lang.ClassCastException:lamdaTurorial.Person不能强制转换为java.lang.Compariable”现在可以了,我只是在我的类中实现Compariable:)
List<Person> sList = customers.stream().sorted().collect(Collectors.toList());