Java 从字符串数组中获取最频繁的值
这个问题的答案已经发布在SO上了,但是我想找到一种不包含像hashmaps这样复杂数据结构的方法。解决方案需要来自ints和足球俱乐部[0]。等于(足球俱乐部[1]) 非常感谢。这是原型:Java 从字符串数组中获取最频繁的值,java,Java,这个问题的答案已经发布在SO上了,但是我想找到一种不包含像hashmaps这样复杂数据结构的方法。解决方案需要来自ints和足球俱乐部[0]。等于(足球俱乐部[1]) 非常感谢。这是原型: import java.util.Arrays; public class WordCount { public static void main(String[] args) { String[] football_club = {"Barcelona", "Real Madrid", "
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 +")");
}
导入java.util.array;
公共类字数
{
公共静态void main(字符串[]args)
{
字符串[]足球俱乐部={“巴塞罗那”、“皇家马德里”、“切尔西”、“皇家马德里”、“巴塞罗那”、“巴塞罗那”};
//首先对数组进行排序,使其具有相同的单词组
数组.排序(足球俱乐部);
字符串结果_club=“”;
字符串字=足球俱乐部[0];
int count=1,winner=0;//字计数器
对于(int i=1;i赢家){//保存赢家
胜利者=计数;
结果俱乐部=单词;
}
word=current;//开始新词计数
计数=1;
}
}
System.out.println(“数组中出现最多的值”+result\u club+(“+winner+”));
}
正如大家所坚持的,您应该使用HashMap
,但是为了回答这个问题,让我们试试这个(未经测试):
字符串mostFrequent=null;
整数频率=0;
Arrays.sort(football_club);//必要时使用副本
整数计数=0;
对于(int i=0;i频率){
mostFrequent=足球俱乐部[i];
频率=计数;
}
计数=0;
}
}
mostFrequent
现在应该包含最频繁的元素。这些注释在映射和效率方面都是正确的,而且它的简单性值得商榷。无论如何,你可以做一些巧妙的技巧,通过返回到字符串操作来获得解决方案,而不需要排序或多个循环,例如
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
}
将为您提供一个字符串,该字符串等于[巴塞罗那、皇家马德里、切尔西、皇家马德里、巴塞罗那、巴塞罗那]
及
将为您提供脚本中每个单词的计数您可以使用
流
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");
//将数组分组到一个包含唯一字符串的映射,并在数组中设置其计数
地图分组=溪流(足球俱乐部)
.collect(Collectors.groupingBy(Function.identity()、Collectors.counting());
//查找具有最大计数的映射条目(如果有)
可选max=grouped.entrySet().stream()
.max(Comparator.comparingLong(条目::getValue));
//geht最大元素的键或默认值(如果没有)
字符串result_club=max.map(条目::getKey).orElse(“Fortuna Düsseldorf”);
这里有一个解决方案,它使用了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);
}
publicstaticvoidmain(字符串[]args)
{
字符串[]足球俱乐部={“巴塞罗那”、“皇家马德里”、“切尔西”、“皇家马德里”、“巴塞罗那”、“巴塞罗那”};
boolean[]seen=新的boolean[football_club.length];
字符串结果_club=null;
int result_count=0;
对于(int i=0;i结果计数){
结果计数=计数;
结果俱乐部=足球俱乐部[i];
}
}
}
系统输出打印LN(结果俱乐部);
}
hashmap是最简单的方法……为什么你不想使用hashmap呢?设置起来并不难。他们希望我能让它变得尽可能简单,所以我必须像他们希望我做的那样去做。你能帮忙吗?如果这不是最简单的解决方案,为什么你认为每个人都会建议使用Map
呢?只要使用它就行了它必须高效吗?如果没有,两个嵌套的for循环就可以了。这里的人速度很快。
int clubCount = (length - arrayToString.replace(club,"").length()) / clubLength;
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");
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);
}