如何使用Stream.flatMap()?

时间:2017-02-16 06:56:17

标签: java java-8 java-stream

我有Stream<SortedSet<String>>,我希望只有一个Stream<String>。我尝试使用flatMap(),但它无法正常工作,因为它无法平滑Sortedset的Stream。

String productName = "p1";
Set<Product> products = new HashSet<>();
products.add(new Product(productName));
Stream<SortedSet<String>> sortedSetStream = products.stream().map(p -> Util.getProductNames(p) );

1 个答案:

答案 0 :(得分:4)

要从这些对象的集合流中获取所有对象的流,您需要展平集合。任何集合都可以转换为流:

#page-wrap {
    display:table;
    width:90%;
    border:1px solid #999;
    border-radius:10px;
    border-spacing:10px;
    margin:auto;
    background-color:#fff;
    box-shadow:6px 6px 6px #999;
 }
#page-wrap div {
    display:table-cell;
    width:33.33%;
    padding:2%;
    border:1px solid #999;
    border-radius:10px;
    background-image:linear-gradient(to bottom,#fff,#ddd);
    box-shadow:inset 0 0 10px #999;
    font-size:1.5vw;
    word-wrap:break-word;
    color:#666; 
 }
@media screen and (max-width:800px) {
#page-wrap div {
    font-size:2.0vw;
  }
 }
@media screen and (max-width:480px) {
#page-wrap div {
    font-size:2.5vw;
  }
 }

或(如果您更喜欢方法参考):

<!DOCTYPE html>
<html  lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>untitled document</title>
<link rel="stylesheet" href="/" media="screen">
<style media="screen">
</style>
 </head>
<body background-color:#f0f0f0;>
<div id="page-wrap">
 <div id="left"></div>
 <div id="right"></div>
 <div id="mid">
  <p>
   Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec 
   ultricies sollicitudin nisi, ut molestie felis adipiscing sit 
   amet. Sed auctor vehicula commodo.
 </p>
</div>
</div>
</body>
</html>