首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在循环中整合冗余信息

在循环中整合冗余信息
EN

Stack Overflow用户
提问于 2014-03-18 03:25:41
回答 1查看 65关注 0票数 1

在Java中,我有一个数组,其中包含一长串有时是冗余的键值对,我希望将它们合并到一个较短的只有唯一键的数组列表中。我如何编辑下面的代码来实现这一点?

以下是outputarr数组中数据的示例:

代码语言:javascript
复制
key value
448 Ethanol
448 Alcohol
448 Alcohol
448 Ethanol
448 Ethanol
448 Alcohol
448 Ethanol
448 Alcohol
448 Ethyl alcohol  

我想将上面的数据合并到一个包含以下数据的数组中:

代码语言:javascript
复制
key value
448 Ethanol; Alcohol; Ethyl alcohol

因此,数组中的9行被合并为arraylist中的一行。并且数组列表中的值是一个连接的字符串"Ethanol; Alcohol; Ethyl alcohol"。但是每个数字键将具有不同数量的值,这些值需要以这种方式连接起来,以便产生单个值字符串,其中列出了与数组中的数字键相关联的唯一名称。

这是我到目前为止拥有的代码,我如何编辑它,使其完成我所描述的?

代码语言:javascript
复制
private static ArrayList<ArrayList<String>> twoDimArrList = new ArrayList<ArrayList<String>>();
public void someMethod(){
    int len = 1000;
    String[][] outputarr = new String[len][2];
    // ommitting code that populates outputarr because the next for loop is what needs help

    for(int r=0;r<len;r++){
        ArrayList<String> temp = new ArrayList<String>();
        if(outputarr[r][0]==outputarr[r+1][0]){
            if(outputarr[r][1].equalsIgnoreCase(outputarr[r+1][1])){
                temp.add(outputarr[r][0]);
                temp.add(outputarr[r][1]);
                twoDimArrList.add(temp);
                r+=1;
            }
        }
    }
}  
EN

回答 1

Stack Overflow用户

发布于 2014-03-18 03:33:46

有许多方法可以做到这一点。一种方法是使用Map<Integer,Set<String>>来保存数据,这将把键映射到值集。

然后,当您读取数据时:

代码语言:javascript
复制
Map<Integer,Set<String>> data = new HashMap<Integer,Set<String>>();

for each item in the file {

    Integer key = ...; // parsed 
    String value = ...; // parsed

    // retrieve set if it exists, create if it doesn't.
    Set<String> values = data.get(key);
    if (values == null) { 
        values = new HashSet<String>();
        data.put(key, values);
    }

    // add value to set
    values.add(value);

}

如果要存储重复的值,请使用List而不是Set。例如,如果您想计算值,请考虑创建一个新类来保存一个值及其计数(使用equals()hashCode()和/或Comparable的适当实现),并存储在读取值时更新的那些值的Set

您也可以设想任意数量的其他方法,但最终都会归结为类似上面的内容:将一个整数ID映射到一个值的集合。

如果您使用third-party multimaps中的一种,您也可以稍微简化代码,这些have实质上实现了上述内容,比如Guava或Apache Commons实现;不幸的是,JDK没有任何内置的多映射(see "Multimaps" section here)。

在遍历容器中的值时,HashMapHashSet不保证任何特定的排序。如果您有特定的排序要求,TreeMap / TreeSet将按升序迭代(由Comparable /Comparator定义的自然顺序),而LinkedHashMap / LinkedHashSet将保持添加元素的顺序。上面的容器可以根据需要替换为这些容器。

对于迭代数据,可以使用标准方法和语法,例如:

代码语言:javascript
复制
for (Map.Entry<Integer,Set<String>> entry : data.entrySet()) {
    Integer key = entry.getKey();
    // ...
    for (String value : entry.getValue()) {
       // ...
    }
}

默认的toString()不能真正猜测您的特定需求,它取决于您迭代您的数据并生成满足您需求的输出。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/22463538

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档