从字符串数组中获取最常见的值

时间:2015-01-21 22:13:34

标签: java

这个问题的答案已经发布在SO上,但我想找到一种不包括像hashmaps这样的复杂数据结构的方法。解决方案需要来自ints和football_club [0] .equals(football_club [1])

String[] football_club = {"Barcelona", "Real Madrid", "Chelsea", "Real Madrid", "Barcelona", "Barcelona"};

//result
Sting result_club = "a value most in the array"
非常感谢你。

5 个答案:

答案 0 :(得分:0)

这是原型:

import java.util.Arrays;

public class WordCount
{
  public static void main(String[] args)
  {
    String[] football_club = {"Barcelona", "Real Madrid", "Chelsea", "Real Madrid", "Barcelona", "Barcelona"};
    // First sort the array to have the same words group togheter
    Arrays.sort(football_club);

    String result_club = "";
    String word = football_club[0];
    int count = 1, winner = 0; // word counters

    for (int i = 1 ; i < football_club.length; i++) {
      String current = football_club[i];
      if (word.equals(current)) {
        count++;
      }
      else { // word changed
        if (count > winner) { // save winner
          winner = count;
          result_club = word;
        }
        word = current; // start new word count
        count = 1;
      }
    }
    System.out.println("A value most appearing in the array " + result_club + "(" + winner +")");
  }

答案 1 :(得分:0)

正如大家所坚持的那样,你应该使用HashMap,但为了这个问题,让我们试试这个(未经测试):

String mostFrequent = null;
int frequency = 0;
Arrays.sort(football_club);    // Use a copy if necessary

int count = 0;
for(int i = 0; i < football_club.length; i++) {
    count++;
    if(i == football_club.length - 1 || !football_club[i].equals(football_club[i + 1])) {
        if(count > frequency) {
            mostFrequent = football_club[i];
            frequency = count;
        }
        count = 0;
    }
}

mostFrequent现在应该包含最常见的元素。

答案 2 :(得分:0)

关于地图和效率的评论是正确的,它可以说是简单的。无论如何,你可以做一些巧妙的技巧并通过回退到字符串操作来获得你的解决方案,而不需要排序或多个循环,例如

public void theMostOftenClub() {
    String[] football_club = {"Barcelona", "Real Madrid", "Chelsea", "Real Madrid", "Barcelona", "Barcelona"};
    String arrayToString = Arrays.toString(football_club);
    int length = arrayToString.length();
    String result_club = "";
    int count = 0;
    for (String club : football_club) {
        int clubLength = club.length();
        int clubCount =  (length - arrayToString.replace(club,"").length()) / clubLength;
        if (count < clubCount) {
            count = clubCount;
            result_club = club;
        }
    }
    System.out.println(result_club); // prints Barcelona
}

两条主线

String arrayToString = Arrays.toString(football_club);

会给你一个等于[Barcelona, Real Madrid, Chelsea, Real Madrid, Barcelona, Barcelona]

的字符串

int clubCount =  (length - arrayToString.replace(club,"").length()) / clubLength;

将为您提供脚本中每个单词的计数

答案 3 :(得分:0)

您可以使用Stream API,但它也可以归结为使用地图,但您没有看到它:

String result_club = Stream.of(football_club)
             .collect(Collectors.groupingBy(Function.identity(), Collectors.counting())) 
             .entrySet().stream()
             .max(Comparator.comparingLong(e -> e.getValue()))
             .map(e -> e.getKey()).orElse(null);

它在部分内容的作用:

// group array to a map holding unique strings an its counts within the array
Map<String, Long> grouped = Stream.of(football_club)
    .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));

// find the entry of the map with the maximum count if there is one
Optional<Entry<String, Long>> max = grouped.entrySet().stream()
    .max(Comparator.comparingLong(Entry::getValue));

// geht the key of the maximum element or a default value if there is none
String result_club = max.map(Entry::getKey).orElse("Fortuna Düsseldorf");

答案 4 :(得分:0)

这是一个使用java.util包中的零功能,只是原始数组和循环的解决方案。

public static void main(String[] args)
{
    String[] football_club = { "Barcelona", "Real Madrid", "Chelsea", "Real Madrid", "Barcelona", "Barcelona" };
    boolean[] seen = new boolean[football_club.length];
    String result_club = null;
    int result_count = 0;
    for (int i = 0; i < football_club.length; i++) {
        if (!seen[i]) {
            seen[i] = true;
            int count = 1;
            for (int j = i + 1; j < football_club.length; j++) {
                if (!seen[j]) {
                    if (football_club[i].equals(football_club[j])) {
                        seen[j] = true;
                        count++;
                    }
                }
            }
            if (count > result_count) {
                result_count = count;
                result_club = football_club[i];
            }
        }
    }
    System.out.println(result_club);
}