如何获取数组中五个最少重复的元素

时间:2017-05-02 19:04:48

标签: java arrays search output

如果我有以下字符串数组。

String inStrings[] = {"A", "B", "C", "D", "E", "F", "G", "H", "A", "B", "C", "D", "E", "A", "B", "C", "D", "A", "B"};

此数组稍后传递给方法,我不知道如何继续。

    static void getColdSearch(String[] inArray){



}

这个方法应该做的是获取数组,获取重复次数最少的字符串,然后在输出中打印出五个最少重复的字符串。重复的字符串不必一个接一个,如果少于五个字符串,那么所有字符串都应该是输出的一部分。例如。如果arraylist看起来像上面的例子,输出应该看起来像这样。

F //(Occurs once)
G //(Occurs once)
H //(Occurs once)
E //(Occurs twice)
D //(if two different elements repeat the same number of times a random one of them should be printed)

我该怎么做?

3 个答案:

答案 0 :(得分:4)

尝试java 8功能

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

public class GroupingDemo {

    public static void getColdSearch(String[] inArray) {
        Map<String, Long> groupingByLetter = Arrays.stream(inArray)
            .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));

        List<String> result = groupingByLetter.entrySet().stream()
            .sorted(Map.Entry.comparingByValue())
            .limit(5)
            .map(Map.Entry::getKey)
            .collect(Collectors.toList());

        System.out.println(result);
    }

    public static void main(String[] args) {
        String inStrings[] = {"A", "B", "C", "D", "E", "F", "G", "H", "A", "B", "C", "D", "E", "A", "B", "C", "D", "A", "B"};
        getColdSearch(inStrings);
    }
}

答案 1 :(得分:1)

使用最大堆(优先级队列)和哈希映射。

创建一个类

         Class WordCount
          {
             String word;
             int count;
           }  
           PriorityQueue<WordCount>queue // queue to save minimum repeated words
           HashMap<String,Integer>map // save data for each word   

循环遍历数组

对于保存在队列中的前5个唯一单词

检查地图中的数据。如果word存在则更新计数

检查队列中的顶部元素。如果单词的计数高于当前索引单词,则从队列中删除单词并添加该单词。 重复该过程直到循环结束。

最后轮询队列中的所有元素

答案 2 :(得分:1)

您可以使用上面概述的Java 8。这是一个解决方案,可能有助于理解如何在Java 7或更早版本中执行相同的操作。另外,我认为了解真正发生的事情是有帮助的。

static void getColdSearch(String[] inArray) {
    Map<String, Integer> counterMap = new HashMap<>();


    // load the array in a Map instance
    for (String in : inArray) {
        if (null != counterMap.putIfAbsent(in, 1) ) {
        counterMap.put(in, counterMap.get(in) + 1);
        }
    }

    // Question: why do we need a priority queue?
    // We could also use sort based on the values. Search 
    // stackoverflow.com for "sorting on map value"
    PriorityQueue<String> heap = new PriorityQueue<>(new Comparator<String>() {

        @Override
        public int compare(String o1, String o2) {
        // sort based on the count.
        return counterMap.get(o1).compareTo(counterMap.get(o2));
        }

    });


    heap.addAll(counterMap.keySet());

    int size = heap.size();
    for (int i = 0; i < size; i++) {
        // you could end it a "5" but I leave that as an exercise.
        String s = heap.poll();
        System.out.println( s + " count: " + counterMap.get(s));
    }
}