【问题标题】:How to count the repetition of duplicate elements that are in arrays?如何计算数组中重复元素的重复?
【发布时间】:2016-03-07 22:55:54
【问题描述】:

我能够计算重复元素,但效率不高。基本上我有一个字符串类型的数组列表。示例:

ArrayList<String> s=new ArrayList<String>();

如果我使用 foreach 打印 s 那么输出是:

[1,2]
[1,4]
[4]
[3,5]

当有多个数组时,计算重复数字的有效方法是什么?任何形式的帮助表示赞赏。

最终输出: 1 是重复 2 次。 2是1次重复。 以此类推

【问题讨论】:

  • 请提出明确的问题。显示您的代码。提供示例输入 + 预期输出。
  • String 中提取数字并使用Map 计算每个数字的出现次数。
  • 如果这些数字的范围很小,你甚至可以使用一个数组,其索引是数字,数据是这个数字的计数。否则,您可以使用 HashMap

标签: java arrays list arraylist collections


【解决方案1】:

如果您愿意使用第三方库,您可以使用支持原始包的GS Collections。 Bag 是一种数据结构,用于跟踪每个唯一元素的出现。使用IntBag 可以减少您的用例所需的装箱量。

CharAdapter remove = CharAdapter.adapt("[]");
IntBag counts =
    Lists.mutable.with("[1,2]", "[1,4]", "[4]", "[3,5]")
        .asLazy()
        .collectWith(StringIterate::rejectChar, remove::contains)
        .flatCollect(StringIterate::csvTokensToList)
        .collectInt(Integer::parseInt)
        .toBag();
Assert.assertEquals(2, counts.occurrencesOf(1));
Assert.assertEquals(1, counts.occurrencesOf(2));

如果您需要按值排序的输出,您可以使用SortedBag&lt;Integer&gt; 代替。但是请注意,这将导致将整数装箱为整数。

CharAdapter remove = CharAdapter.adapt("[]");
SortedBag<Integer> counts =
    Lists.mutable.with("[1,2]", "[1,4]", "[4]", "[3,5]")
        .asLazy()
        .collectWith(StringIterate::rejectChar, remove::contains)
        .flatCollect(StringIterate::csvTokensToList)
        .collect(Integer::parseInt)
        .toSortedBag();
Assert.assertEquals(2, counts.occurrencesOf(1));
Assert.assertEquals(1, counts.occurrencesOf(2));
System.out.println(counts.toStringOfItemToCount());

输出:

{1=2, 2=1, 3=1, 4=2, 5=1}

注意:我是 GS Collections 的开发人员

【讨论】:

    【解决方案2】:

    你可以使用a counting collector:

    public static void main(String[] args) {
      List<String> s = Arrays.asList("[1,2]", "[1,4]", "[4]", "[3,5]");
      Map<Integer, Long> occurences = s.stream()
                      .flatMap(abc::parseString)
                      .collect(groupingBy(i -> i, counting()));
      System.out.println("occurences = " + occurences);
    }
    
    private static Stream<Integer> parseString(String s) {
      String[] numbers = s.substring(1, s.length() - 1).split(",");
      return Arrays.stream(numbers).map(Integer::parseInt);
    }
    

    输出:

    出现次数 = {1=2, 2=1, 3=1, 4=2, 5=1}

    【讨论】:

      猜你喜欢
      • 2010-10-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-04
      • 1970-01-01
      • 2013-08-20
      • 2016-04-21
      • 2020-12-01
      相关资源
      最近更新 更多