我有一个如下所示的数组
String[] football_club = {"Barcelona", "Real Madrid", "Chelsea", "Real Madrid", "Barcelona", "Barcelona"};
//result
Sting result_club = "a value most in the array"
在上面的数组中,"巴塞罗那" 经常出现在该数组中。
如何编写代码来查找数组中出现最频繁的值?
我有一个如下所示的数组
String[] football_club = {"Barcelona", "Real Madrid", "Chelsea", "Real Madrid", "Barcelona", "Barcelona"};
//result
Sting result_club = "a value most in the array"
在上面的数组中,"巴塞罗那" 经常出现在该数组中。
如何编写代码来查找数组中出现最频繁的值?
HashMap<String,Integer>
。如果这个 String 已经出现在 map 中,就将其对应的 key 值加一,否则将其添加到 map 中。put("Barcelona", 1);
接下来,假设又是"巴塞罗那",你可以执行以下操作:
put("Barcelona", get("Barcelona") + 1);
由于“巴塞罗那”的键是1,现在当您输入它时,该键将变为2。
import java.util.HashMap;
/**
* Created with IntelliJ IDEA.
* User: Alexander.Iljushkin
* Date: 23.10.13
* Time: 11:32
*/
public class TestClass1 {
public static void main(String[] args) {
String[] football_club = {"Barcelona", "Real Madrid", "Chelsea", "Real Madrid", "Barcelona", "Barcelona"};
HashMap<String, Integer> map = new HashMap<String, Integer>();
String tempStr;
for (int i = 0; i < football_club.length; i++)
{
tempStr = football_club[i];
if(map.containsKey(tempStr))
{
map.put(tempStr, map.get(tempStr) + 1);
}
else
{
map.put(tempStr,1);
}
}
System.out.print(map.toString());
}
}
数量
对地图中的项进行排序(这只是一个例子,在自学的过程中可以更改):public class Testing {
public static void main(String[] args) {
HashMap<String,Double> map = new HashMap<String,Double>();
ValueComparator bvc = new ValueComparator(map);
TreeMap<String,Double> sorted_map = new TreeMap<String,Double>(bvc);
map.put("A",99.5);
map.put("B",67.4);
map.put("C",67.4);
map.put("D",67.3);
System.out.println("unsorted map: "+map);
sorted_map.putAll(map);
System.out.println("results: "+sorted_map);
}
}
class ValueComparator implements Comparator<String> {
Map<String, Double> base;
public ValueComparator(Map<String, Double> base) {
this.base = base;
}
// Note: this comparator imposes orderings that are inconsistent with equals.
public int compare(String a, String b) {
if (base.get(a) >= base.get(b)) {
return -1;
} else {
return 1;
} // returning 0 would merge keys
}
}
当你对哈希表进行排序后,只需获取第一个键,这将是最频繁的键。
private String getRepeatedString(String[] football_club) {
List<String> List1 = Arrays.asList(football_club);
HashMap<String, Integer> data = new HashMap<String, Integer>();
int max = 0;
for (String string : List1) {
int count = 1;
if (data.containsKey(string)) {
count = data.get(string) + 1;
data.put(string, count);
} else {
data.put(string, 1);
}
if (max < count)
max =count;
}
System.out.println(data);
for (Entry<String, Integer> entry : data.entrySet()) {
if (max == entry.getValue()) {
return entry.getKey();
}
}
return null;
}
String[] football_club = {"Barcelona", "Real Madrid", "Chelsea", "Real Madrid", "Barcelona", "Barcelona"};
List<String> l = Arrays.asList(football_club);
Set<String> s = new HashSet<String>(l);
for (String key : s) {
int count = Collections.frequency(l, key);
System.out.println("Found '" + key + "' " + count + " times.");
}