【问题标题】:Extracting map values as ArrayList from LinkedHashMap从 LinkedHashMap 中提取地图值作为 ArrayList
【发布时间】:2017-09-09 01:44:45
【问题描述】:

我创建了一个简单的类 MapExtension 来适应将 4 个值传递给列表视图适配器,并使用 LinkedHashmap 添加 MapExtension 的 ArrayList。

public class MapExtension {
private String studname;
private String studnumber;
private String schedule;


public MapExtension(String studname, String studnumber, String schedule) {
    this.studname = studname;
    this.studnumber= studnumber;
    this.schedule= schedule;
}

public String getStudname () {
    return studname;
}

public String getStudnumber() {
    return studnumber;
}

public String getSchedule() {
    return schedule;
}

}

每当我尝试从返回 Collections 的 LinkedHashMap 中提取 ArrayList<MapExtension> 时,我都会从不同的试验中得到这些错误(在 cmets 中):

ListViewAdapter(Context context, LinkedHashMap<Integer, ArrayList<MapExtension>> mValues) {
    super(context, R.layout.listview_layout, mValues.keySet().toArray());
    this.context = context;

    //java.lang.ClassCastException: java.util.HashMap$Values 
    //cannot be cast to java.util.ArrayList
    ArrayList mValues = (ArrayList) mValues.values();

    // says incompatible as it will become ArrayList<ArrayList<MapExtension>>
    ArrayList<MapExtension> mValues = new ArrayList<>(mValues.values());      
}

我怎样才能成功地检索它并放入它的兼容类型?

提前致谢。

【问题讨论】:

    标签: java android listview arraylist collections


    【解决方案1】:

    mValues 中的每一个value 都是一个ArrayList&lt;MapExtensions&gt;,而values 返回一个Collection&lt;V&gt;,所以你应该可以做到..

    Collection<ArrayList<MapExtensions>> localVar = mValues.values();
    

    如果你想扁平化你的嵌套数组,你可以查看流的 flatMap() 方法。 Here is one person's blog on that。顺便说一句,Kotlin 集合有一个 flatMap() 扩展方法,适用于集合。

    【讨论】:

    • 这将我引向Usage of API documented as @since 1.8+。我还不能让它工作,因为 Android Studio 不允许我使用 1.8 版,但只能使用 1.7 版。
    【解决方案2】:

    如果我理解正确,给定LinkedHashMap&lt;Integer, ArrayList&lt;MapExtension&gt;&gt; mValues,您希望ArrayList&lt;MapExtension&gt; 将输入映射的值展平。使用 Java 8,您可以轻松地做到这一点:

    ArrayList<MapExtension> extensions = mValues .values() .stream() .collect(ArrayList::new, ArrayList::addAll, ArrayList::addAll);

    一个小提示:您应该针对接口进行编程,因此不要在您的类型中使用ArrayList,而是考虑使用List,这样您就不会在任何地方都被一个特定的具体实现所束缚。

    【讨论】:

    • 鉴于 SO 使用List&lt;MapExtension&gt; 可能会更好,是flapMap(List::stream) 然后collect(Collectors.toList()) 更好吗?
    • 是的,在这种情况下它确实变得更简单了。
    • 感谢您的提示。我通过使用该代码获得了Usage of API documented as @since 1.8+,而 AS 只允许我使用 1.7。
    猜你喜欢
    • 2022-11-26
    • 1970-01-01
    • 2014-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多