Java流和列表列表

时间:2019-02-05 11:39:04

标签: java java-stream

由于某种原因,我无法解决如何使用流将深度嵌套的列表转换为新列表的问题。

   every A in List<A> contains -> 
   List<B> where every B contains -> 
   List<C> where every C contains -> List<String>

我尝试了许多不同的迭代,例如:

  List<String> newlist =  listA.getB()
                   .stream()
                   .filter(b -> b.getC()
                   .stream()
                   .filter(c -> c.getPeople)
                   .collect(Collectors.toList())

我很困惑... 我可以使用for循环轻松地做到这一点,但是我听说流简单易用,我想开始更多地使用它们。

1 个答案:

答案 0 :(得分:11)

您应该使用string inClause = string.Join(",", products.Select(x => x.Categories.First().CategoryId).Distinct().Select(x => $"'{x}'")); List<CategoryName> navigation = new List<CategoryName>(); using (DbCommand command = db.Database.GetDbConnection().CreateCommand()) { command.CommandText = $"WITH NestedCategories AS (SELECT * FROM Categories WHERE Id IN ({inClause}) UNION ALL SELECT t.* FROM Categories t INNER JOIN NestedCategories c On c.ParentId = t.Id) SELECT DISTINCT c.Id, c.Name, c.ParentId FROM NestedCategories c"; await db.Database.GetDbConnection().OpenAsync(); DbDataReader reader = await command.ExecuteReaderAsync(); while (await reader.ReadAsync()) navigation.Add(new CategoryName() { Id = reader.GetInt32(0), Name = reader.GetString(1), ParentId = await reader.IsDBNullAsync(2) ? null : await reader.GetFieldValueAsync<int?>(2) }); }

flatMap