0

我有以下格式的excel

  customers  users
  customer1  user1
  customer1  user2
  customer2  user3
  customer3  user4
  customer3  user5

我将上面的内容解析成一个字符串数组。我需要它在这样的字符串中

script.bat -c customer1 -u user1 user2
script.bat -c customer2 -u user3
script.bat -c customer3 -u user4 user5

本质上,我想检查所有“客户 1”并将与“客户 1”关联的任何用户添加到字符串中。该字符串很容易,但是要让它们到达那里,我不确定是否最好使用 Hashmap 或类似的东西,以便我可以轻松地比较和查找值。

4

1 回答 1

0

使用 aMap将您的独特客户与您的用户一起编译,然后遍历地图并格式化您String的 s。

使用您的输入作为的示例String[]

public static void main(String[] args) {
    final String[] strings = {"customer1  user1",
        "customer1  user2",
        "customer2  user3",
        "customer3  user4",
        "customer3  user5"};

    final Map<String, Set<String>> concatentatingMap = new HashMap<String, Set<String>>() {
        @Override
        public Set<String> get(Object key) {
            Set<String> strings = super.get(key);
            if (strings == null) {
                strings = new LinkedHashSet<>();
                put((String) key, strings);
            }
            return strings;
        }
    };

    for (final String s : strings) {
        final String[] split = s.split("\\s++");
        concatentatingMap.get(split[0]).add(split[1]);
    }
    final MessageFormat messageFormat = new MessageFormat("script.bat -c {0} -u {1}");
    for (final Entry<String, Set<String>> entry : concatentatingMap.entrySet()) {
        final String customer = entry.getKey();
        final StringBuilder usersBuilder = new StringBuilder();
        final Iterator<String> iter = entry.getValue().iterator();
        while (iter.hasNext()) {
            usersBuilder.append(iter.next());
            if (iter.hasNext()) {
                usersBuilder.append(" ");
            }
        }
        System.out.println(messageFormat.format(new Object[]{customer, usersBuilder.toString()}));
    }
}

输出:

script.bat -c customer3 -u user4 user5
script.bat -c customer2 -u user3
script.bat -c customer1 -u user1 user2
于 2013-03-26T13:01:11.493 回答