流列表

时间:2018-03-28 02:16:55

标签: java java-8 java-stream

List<String> list2 = Arrays.asList("hello", "hi", "你好");  
List<String> list3 = Arrays.asList("zhangsan", "lisi", "wangwu", "zhaoliu");  

List<Stream<String>> list2Result = list2.stream().map(item -> list3.stream().map(item2 -> item + " " + item2)).collect(Collectors.toList());

list2Result.forEach(item -> item.collect(Collectors.toList()));
list2Result.forEach(item -> item.forEach(System.out::println));

我必须将list2Result转换为List<List<String>>,但我不能使用foreach来打印它。

  

线程“main”中的异常java.lang.IllegalStateException:stream已经被操作或关闭          at java.util.stream.AbstractPipeline.evaluate(Unknown Source)          at java.util.stream.ReferencePipeline.forEach(Unknown Source)          在com.singhand.proxyServer.Main.lambda $ 15(Main.java:61)          at java.util.ArrayList.forEach(Unknown Source)          在com.singhand.proxyServer.Main.main(Main.java:61)

1 个答案:

答案 0 :(得分:1)

您无法两次操作相同的Stream

尝试在第一个map中收集列表。

List<List<String>> list2Result = list2.stream()
        .map(item -> list3.stream()
            .map(item2 -> item + " " + item2)
            .collect(Collectors.toList()))
        .collect(Collectors.toList());

以相同的方式打印列表列表

list2Result.forEach(item -> item.forEach(System.out::println));

如果你想要一个展平列表,尝试在flatMap之前使用它来收集列表。List<String> list2Result = list2.stream() .map(item -> list3.stream() .flatMap(item2 -> item + " " + item2)) .collect(Collectors.toList()); 将多个流展开为一个。

List

然后你将拥有可以打印的list2Result.forEach(System.out::println); 个字符串。

            string emailFrom =  "abc@hotmail.com";
            string emailTo = "test@company.com.my";
            string emailSubject = "e-Receipt";
            string emailDescription = "Dear Customer, \n Attached is your e-Receipt. Thank You.";

            StreamReader reader = File.OpenText("C:/file/invoice.html");
            MailMessage message = new MailMessage(emailFrom, emailTo, emailSubject, reader.ReadToEnd());
            message.IsBodyHtml = true;

            Attachment data = new Attachment(path+filename, MediaTypeNames.Application.Octet);
            ContentDisposition disposition = data.ContentDisposition;
            disposition.CreationDate = System.IO.File.GetCreationTime(path + filename);
            disposition.ModificationDate = System.IO.File.GetLastWriteTime(path + filename);
            disposition.ReadDate = System.IO.File.GetLastAccessTime(path + filename);
            message.Attachments.Add(data);