【问题标题】:Convert String to HashMap/MultiSet?将字符串转换为 HashMap/MultiSet?
【发布时间】:2013-06-26 15:44:51
【问题描述】:

将长字符串转换为包含单词和计数的数据结构的最佳方法是什么。

我会做 .split(" ") 来分割空格并大概创建一个数组列表,然后可能会通过数组列表并将每个项目添加到哈希图或多重集?我不确定最好的方法是什么/是否可以直接使用某种哈希图而不先创建数组列表。

谢谢!

【问题讨论】:

  • 你能举例说明你的数据是什么样的吗?
  • 只是很多很多的字符串,比如“word bla bla word another word /moren+!*&^@#random words”?
  • 您如何定义“最佳”?尽可能快,使用尽可能少的内存或易于阅读和理解的代码?
  • 好吧,我不太担心它是最优的,任何可接受的方式都好吗?我只是不确定人们通常会为这种常见的任务做什么。可能我会制作arraylist,然后通过arraylist并将每个项目添加到带有计数的hashmap?然后为不同的字符串合并多个哈希图

标签: java split hashmap multiset


【解决方案1】:

如果你指的是GuavaMultiset,这只是一行

HashMultiset.create(
  Splitter.on(CharMatcher.WHITESPACE).omitEmptyStrings()
    .split(string));

【讨论】:

  • 有趣,这看起来很简单,但我可能会选择另一种情况以避免使用我的代码的人没有番石榴的情况
【解决方案2】:
import java.util.HashMap;
import java.util.Map;

public class Test {
    private static Map<String, Integer> count = new HashMap<String, Integer>();

    public static void main(String[] args) {
        addToCountMap("This is my test string and it contains Test and test and string and some more");
        addToCountMap("This is my test string and it contains Test and test and string and some more");
        addToCountMap("This is my test string and it contains Test and test and string and some more");
        addToCountMap("This is my test string and it contains Test and test and string and some more");
        addToCountMap("This is my test string and it contains Test and test and string and some more");

        mergeWithCountMap(count);

        System.out.println(count);
    }

    private static void addToCountMap(String test) {
        String[] split = test.split(" ");
        for (String string : split) {
            if (!count.containsKey(string)) {
                count.put(string, 0);
            }
            count.put(string, count.get(string) + 1);
        }
    }

    private static void mergeWithCountMap(Map<String, Integer> mapToMerge) {
        for (String string : mapToMerge.keySet()) {
            if (!count.containsKey(string)) {
                count.put(string, 0);
            }
            count.put(string, count.get(string) + mapToMerge.get(string));
        }
    }
}

【讨论】:

  • count.put(sting, 1) 如果你想要计数中的实际数字。
  • 是的,这看起来像我想要的。我唯一的后续问题是,我将如何合并两个哈希图?我可能需要为来自不同来源的哈希图执行此操作
  • 呃你是什么意思,我不确定,我想要出现的总数,所以我想我们需要在现有计数上加 1?
  • 当您找到第一个匹配项时,您希望从 1 开始计数。
  • @Lemonio 添加了合并示例。
猜你喜欢
  • 1970-01-01
  • 2014-03-10
  • 1970-01-01
  • 2021-01-13
  • 1970-01-01
  • 2021-04-21
  • 2020-07-26
  • 2012-05-17
相关资源
最近更新 更多