发生数组中每个项目的Java计数
有什么方法来计算数组中每个项目的发生?
可以说我有:
String[] array = {"name1","name2","name3","name4", "name5"};
这里的输出将是:
name1 1 name2 1 name3 1 name4 1 name5 1
如果我有:
String[] array = {"name1","name1","name2","name2", "name2"};
输出将是:
name1 2 name2 3
这里的输出只是为了演示预期的结果。
您可以使用Google Collections / Guava中的MultiSet
或Apache Commons中的Bag
。
如果您有一个集合而不是一个数组,则可以使用addAll()
将全部内容添加到上述数据结构中,然后将count()
方法应用于每个值。 SortedMultiSet
或SortedBag
会按照定义的顺序为您提供项目。
Google Collections实际上具有从数组到SortedMultiset
非常方便的方法。
List asList = Arrays.asList(array); Set<String> mySet = new HashSet<String>(asList); for(String s: mySet){ System.out.println(s + " " +Collections.frequency(asList,s)); }
用java-8 ,你可以这样做:
String[] array = {"name1","name2","name3","name4", "name5", "name2"}; Arrays.stream(array) .collect(Collectors.groupingBy(s -> s)) .forEach((k, v) -> System.out.println(k+" "+v.size()));
输出:
name5 1 name4 1 name3 1 name2 2 name1 1
它所做的是:
- 从原始数组创build一个
Stream<String>
- 按身份对每个元素进行分组,得到一个
Map<String, List<String>>
- 对于每个键值对,打印键和列表的大小
如果你想得到一个包含每个单词出现次数的Map
,可以这样做:
Map<String, Long> map = Arrays.stream(array) .collect(Collectors.groupingBy(s -> s, Collectors.counting()));
欲了解更多信息:
-
Stream
-
Collectors
希望它有帮助! 🙂
我将使用一个哈希表与密钥采取数组元素(这里string)和价值整数。
然后按照如下方式浏览列表:
for(String s:array){ if(hash.containsKey(s)){ Integer i = hash.get(s); i++; }else{ hash.put(s, new Interger(1)); }
我为此写了一个解决scheme来练习自己。 它看起来不像发布的其他答案那么棒,但是我会发布它,然后学习如何使用其他方法来做到这一点。 请享用:
public static Integer[] countItems(String[] arr) { List<Integer> itemCount = new ArrayList<Integer>(); Integer counter = 0; String lastItem = arr[0]; for(int i = 0; i < arr.length; i++) { if(arr[i].equals(lastItem)) { counter++; } else { itemCount.add(counter); counter = 1; } lastItem = arr[i]; } itemCount.add(counter); return itemCount.toArray(new Integer[itemCount.size()]); } public static void main(String[] args) { String[] array = {"name1","name1","name2","name2", "name2", "name3", "name1","name1","name2","name2", "name2", "name3"}; Arrays.sort(array); Integer[] cArr = countItems(array); int num = 0; for(int i = 0; i < cArr.length; i++) { num += cArr[i]-1; System.out.println(array[num] + ": " + cArr[i].toString()); } }
使用HashMap它是在公园散步。
main(){ String[] array ={"a","ab","a","abc","abc","a","ab","ab","a"}; Map<String,Integer> hm = new HashMap(); for(String x:array){ if(!hm.containsKey(x)){ hm.put(x,1); }else{ hm.put(x, hm.get(x)+1); } } System.out.println(hm); }
这里是我的解决scheme – 该方法采用一个整数数组(假设范围在0到100之间)作为input,并返回每个元素的出现次数。
比方说input是[21,34,43,21,21,21,45,65,65,76,76,76]
。 所以输出将在一个映射中,它是: {34=1, 21=4, 65=2, 76=3, 43=1, 45=1}
public Map<Integer, Integer> countOccurrence(int[] numbersToProcess) { int[] possibleNumbers = new int[100]; Map<Integer, Integer> result = new HashMap<Integer, Integer>(); for (int i = 0; i < numbersToProcess.length; ++i) { possibleNumbers[numbersToProcess[i]] = possibleNumbers[numbersToProcess[i]] + 1; result.put(numbersToProcess[i], possibleNumbers[numbersToProcess[i]]); } return result; }
你可以通过使用Arrays.sort和recursion来完成。 同样的酒,但在不同的瓶子….
import java.util.Arrays; public class ArrayTest { public static int mainCount=0; public static void main(String[] args) { String prevItem = ""; String[] array = {"name1","name1","name2","name2", "name2"}; Arrays.sort(array); for(String item:array){ if(! prevItem.equals(item)){ mainCount = 0; countArray(array, 0, item); prevItem = item; } } } private static void countArray(String[] arr, int currentPos, String item) { if(currentPos == arr.length){ System.out.println(item + " " + mainCount); return; } else{ if(arr[currentPos].toString().equals(item)){ mainCount += 1; } countArray(arr, currentPos+1, item); } } }
您可以使用如下例所示的哈希映射:
import java.util.HashMap; import java.util.Set; /** * * @author Abdul Rab Khan * */ public class CounterExample { public static void main(String[] args) { String[] array = { "name1", "name1", "name2", "name2", "name2" }; countStringOccurences(array); } /** * This method process the string array to find the number of occurrences of * each string element * * @param strArray * array containing string elements */ private static void countStringOccurences(String[] strArray) { HashMap<String, Integer> countMap = new HashMap<String, Integer>(); for (String string : strArray) { if (!countMap.containsKey(string)) { countMap.put(string, 1); } else { Integer count = countMap.get(string); count = count + 1; countMap.put(string, count); } } printCount(countMap); } /** * This method will print the occurrence of each element * * @param countMap * map containg string as a key, and its count as the value */ private static void printCount(HashMap<String, Integer> countMap) { Set<String> keySet = countMap.keySet(); for (String string : keySet) { System.out.println(string + " : " + countMap.get(string)); } } }
有几种方法可以帮助,但这是一个使用for循环。
import java.util.Arrays; public class one_dimensional_for { private static void count(int[] arr) { Arrays.sort(arr); int sum = 0, counter = 0; for (int i = 0; i < arr.length; i++) { if (arr[0] == arr[arr.length - 1]) { System.out.println(arr[0] + ": " + counter + " times"); break; } else { if (i == (arr.length - 1)) { sum += arr[arr.length - 1]; counter++; System.out.println((sum / counter) + " : " + counter + " times"); break; } else { if (arr[i] == arr[i + 1]) { sum += arr[i]; counter++; } else if (arr[i] != arr[i + 1]) { sum += arr[i]; counter++; System.out.println((sum / counter) + " : " + counter + " times"); sum = 0; counter = 0; } } } } } public static void main(String[] args) { int nums[] = { 1, 1, 1, 1, 2, 2, 2, 3, 3, 4, 5, 5, 5, 5, 6 }; count(nums); } }
这是我在Python中使用的一个简单的脚本,但它可以很容易地适应。 没有什么奇特的。
def occurance(arr): results = [] for n in arr: data = {} data["point"] = n data["count"] = 0 for i in range(0, len(arr)): if n == arr[i]: data["count"] += 1 results.append(data) return results
你可以使用简单的技术使用HashMap
public class HashMapExample { public static void main(String[] args) { stringArray(); } public static void stringArray() { String[] a = {"name1","name2","name3","name4", "name5"}; Map<String, String> hm = new HashMap<String, String>(); for(int i=0;i<a.length;i++) { String bl=(String)hm.get(a[i]); if(bl==null) { hm.put(a[i],String.valueOf(1)); }else { String k=hm.get(a[i]); int j=Integer.valueOf(k); hm.put(a[i],String.valueOf(j+1)); } } //hm.entrySet(); System.out.println("map elements are "+hm.toString()); } }
//使用Hashset或map或Arraylist的答案
public class Count { static String names[] = {"name1","name1","name2","name2", "name2"}; public static void main(String args[]) { printCount(names); } public static void printCount(String[] names){ java.util.Arrays.sort(names); int n = names.length, c; for(int i=0;i<n;i++){ System.out.print(names[i]+" "); } System.out.println(); int result[] = new int[n]; for(int i=0;i<n;i++){ result[i] = 0; } for(int i =0;i<n;i++){ if (i != n-1){ for(int j=0;j<n;j++){ if(names[i] == names[j] ) result[i]++; } } else if (names[n-2] == names[n-1]){ result[i] = result[i-1]; } else result[i] = 1; } int max = 0,index = 0; for(int i=0;i<n;i++){ System.out.print(result[i]+" "); if (result[i] >= max){ max = result[i]; index = i; } } } }
它可以用一个非常简单的方法使用集合,请find下面的代码
String[] array = {"name1","name1","name2","name2", "name2"}; List<String> sampleList=(List<String>) Arrays.asList(array); for(String inpt:array){ int frequency=Collections.frequency(sampleList,inpt); System.out.println(inpt+" "+frequency); }
这里的输出将会像name1 2 name1 2 name2 3 name2 3 name2 3
为了避免打印多余的键,使用HashMap并获得所需的输出
你可以使用HashMap,其中Key是你的string和值count。
import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; public class MultiString { public HashMap<String, Integer> countIntem( String[] array ) { Arrays.sort(array); HashMap<String, Integer> map = new HashMap<String, Integer>(); Integer count = 0; String first = array[0]; for( int counter = 0; counter < array.length; counter++ ) { if(first.hashCode() == array[counter].hashCode()) { count = count + 1; } else { map.put(first, count); count = 1; } first = array[counter]; map.put(first, count); } return map; } /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub String[] array = { "name1", "name1", "name2", "name2", "name2", "name3", "name1", "name1", "name2", "name2", "name2", "name3" }; HashMap<String, Integer> countMap = new MultiString().countIntem(array); System.out.println(countMap); } } Gives you O(n) complexity.