【问题标题】:Filter a List<> content in to dictionary in Java将 List<> 内容过滤到 Java 中的字典中
【发布时间】:2014-07-07 12:52:09
【问题描述】:

我有一个特定类型对象的列表,如下所示:

List<Code>

Code类的属性如下;

private Integer id;
private Amp amp;
private FF ff;
private Imp imp;
private Board b;
private Line line;
private int interface;
private String interfaceType;
private boolean chained;

我想根据界面过滤这个列表。接口可以从 0-7 变化,因此我想创建一个字典作为

Dictionary<int, List<Code>>

如何根据界面过滤列表创建字典?

提前感谢您的回答。

【问题讨论】:

  • 您应该将您的自定义Comparator 提供给sort 方法
  • 你试过什么?我不太清楚你在问什么,但也许显示一些你尝试过的代码可以解决问题。
  • 请注意,这不会编译,因为interface 是关键字,您将其用作变量名。其次,它不会编译,因为您没有在 Dictionary 中使用 Integer 包装类(您不能使用原始类型作为参数化)。

标签: java list dictionary collections


【解决方案1】:

我认为您正在寻找这样的东西:

List<Code> codes = ...;
Map<Integer, List<Code>> grouped = new HashMap<>();
for (Code code : codes) {
    if (! grouped.containsKey(code.getInterface()) {
        grouped.put(code.getInterface(), new ArrayList<Code>());
    }
    grouped.get(code.getInterface()).add(code);
}

【讨论】:

  • 原始ArrayList?为什么?
  • @Zhuinden 因为错字。固定。
【解决方案2】:

您可以使用 guava Multimaps 实用程序来表达您的映射。然后将结果放入字典中。

import com.google.common.base.Function;
import com.google.common.collect.ImmutableListMultimap;
import com.google.common.collect.Multimaps;

public class Code {

    public int getInterface() {...}
    ...

    public static void main(String[] args) {
        List<Code> codes = new ArrayList<Code>();
        ImmutableListMultimap<Integer, Code> listMultimap = Multimaps.index(codes, new Function<Code, Integer>() {
            @Override
            public Integer apply(Code code) {
                return code.getInterface();
            }
        });

        Hashtable<Integer, List<Code>> dictionary = new Hashtable<Integer, List<Code>>(Multimaps.asMap(listMultimap));
    }
}

【讨论】:

    【解决方案3】:
    List<Code> codes = <your_init>;
    Dictionary<Integer, List<Code>> dict = new Hashtable<>();
    
    //initialize dictionary
    for ( int i = 0; i < 8; ++i )
    {
      dict.put( i, new ArrayList<Code>() );
    }
    
    //iterate list and fill dictionary
    for (Code code : codes )
    {
      List<Code> item = dict.get( code.interface );
      item.add( code );
      dict.put( code.interface, item );
    }
    

    【讨论】:

    • 这个允许非对象模板参数(int)的“字典”是什么?
    • 通用参数不能是原始的。 int -> Integer
    • 另外,Dictionary 是abstract,不能实例化。
    • 您不必从字典中提取并重新插入列表来添加项目。此外,如果接口编号大于 7,则会中断。
    • 感谢 cmets,我编辑了我的帖子。至于@tobias_k 评论,我假设接口不会是0-7,正如第一篇文章中所说的那样。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-08-01
    • 2021-12-18
    • 2011-08-23
    • 2014-07-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多