【问题标题】:Is there a way to get the highest number of occurrence of elements in an array?有没有办法让数组中的元素出现次数最多?
【发布时间】:2016-02-07 19:22:54
【问题描述】:

我有这个示例函数来获取列表中投票最多的名字,.. 只要我知道列表中的人的名字,它应该像下面这样简单。

public static String getHighestVotes(final List<String> votedNames) {

    int a = Collections.frequency(votedNames, "Ann");
    int b= Collections.frequency(votedNames, "Annie");
    int c = Collections.frequency(votedNames, "Ana");

   //some logic code here..  

    return "";
}

但是,我没有,所以下面的代码没有用。虽然我可以通过某些方式做到这一点.. 做循环等。如果列表的长度达到大约数百万,性能将是我的问题。 那么有没有办法减少这个工作呢?或者我真的应该去计算唯一性等等。

【问题讨论】:

  • 您只需要一个循环来填充您计算出现次数的地图(地图键将是名称,值是遇到的次数)。然后选择出现次数最多的地图条目。

标签: java arrays string list collections


【解决方案1】:

您说 List 将包含数百万个数据,在这种情况下使用 paralleStream() 将比 stream() 更有利。

List <String> list = new ArrayList < String > ();

for (int i = 1; i <= 3000; i++)
 list.add("a");

for (int i = 1; i <= 2000; i++)
 list.add("b");

for (int i = 1; i <= 1000; i++)
 list.add("c");

long start = System.currentTimeMillis();

Map <String, Long> countListSequence = list.stream()
    .collect(Collectors.groupingBy(e -> e, Collectors.counting()));

long end = System.currentTimeMillis();

System.out.println("Time taken by stream() " + (end - start) + " millisec data " + countListSequence);

long start1 = System.currentTimeMillis();

Map <String, Long> countListparallel = list.parallelStream()
    .collect(Collectors.groupingBy(e -> e, Collectors.counting()));

long end1 = System.currentTimeMillis();

System.out.println("Time taken by parallelStream() " + (end1 - start1) + " millisec data " + countListparallel);

输出

Time taken in by stream() 93 millisec data {a=3000, b=2000, c=1000}
Time taken by parallelStream() 11 millisec data {a=3000, b=2000, c=1000}

【讨论】:

    【解决方案2】:

    Java8 确实有一个简单的选择:

        Map<String, Long> result = votedNames.stream().collect(
                Collectors.groupingBy(s -> s, 
                               Collectors.counting()));
    

    【讨论】:

      【解决方案3】:

      获取您的姓名列表并将其添加到地图中。例如:

      Map<String, Integer> res = new HashMap<>();
      votedNames.forEach( s -> {
        if(res.get(s) == null) // initialize
        // increment count for word
      });
      

      结果将是一个哈希图,其中包含每个单词的计数。

      【讨论】:

      • 或者使用缩减来代替:Map&lt;String, Long&gt; res = votedNames.stream().collect(groupingBy(n -&gt; n, counting()));
      • Map&lt;String, Integer&gt; res = new HashMap&lt;&gt;(); for (String s : votedNames) res.merge(s, 1, Integer::sum);
      猜你喜欢
      • 2021-12-19
      • 2010-11-06
      • 2011-04-17
      • 2013-05-01
      • 2019-04-29
      • 2020-05-17
      • 2013-10-13
      相关资源
      最近更新 更多