Heim  >  Fragen und Antworten  >  Hauptteil

java - List<List<model>>如何更快捷的取里面的model?

访问接口返回数据类型为List<List<model>>,现在想将其中的model插入数据库,感觉一点点循环有点傻,0.0...,各位有没有其他的方法?
PHP中文网PHP中文网2741 Tage vor590

Antworte allen(5)Ich werde antworten

  • PHP中文网

    PHP中文网2017-04-18 10:55:31

    C#的话:

    var flat = list.SelectMany(l=>l).ToList();

    Java的话:

    List<model> flat = list.stream().flatMap(List::stream).collect(Collectors.toList());

    Antwort
    0
  • 高洛峰

    高洛峰2017-04-18 10:55:31

    list.stream().flatMap(model-> model.stream()).forEach(System.out::println);

    Antwort
    0
  • 高洛峰

    高洛峰2017-04-18 10:55:31

    数据结构使然,循环吧

    Antwort
    0
  • 天蓬老师

    天蓬老师2017-04-18 10:55:31

            public static IEnumerable<T> GetItems<T>(this List<List<T>> list)
            {
                foreach (var child in list)
                {
                    foreach (var item in child)
                    {
                        yield return item;
                    }
                }
            }
    
            public static IEnumerable<T> GetNestItems<T>(this System.Collections.IList list)
            {
                Type type = null;
    
                foreach (var item in list)
                {
                    if (type == null) type = item.GetType();
    
                    if (type == typeof(T))
                    {
                        yield return (T)item;
                    }
                    else if (type.GetGenericTypeDefinition() == typeof(List<>))
                    {
                        var items = GetNestItems<T>((System.Collections.IList)item);
    
                        foreach (var t in items)
                        {
                            yield return t;
                        }
                    }
                }
            }

    Antwort
    0
  • 阿神

    阿神2017-04-18 10:55:31

    自己要不循环。要不接住其他函数来帮你完成循环。

    Antwort
    0
  • StornierenAntwort