![](/img/trans.png)
[英]How to find the number of times a specific element occurs in an Array list in Java
[英]How do you find a specific value in an array/string and how many times it occurs in the array/string
我在嘗試編碼程序的一部分時遇到困難,在該程序中,我檢查是否某些輸入在數組/字符串中(我可以將數組轉換為字符串)。 這也不會阻止他們,我需要弄清楚我輸入的值在該數組中的次數。 例如:我有一個2 2 3 1 2的數組。我輸入2,我想讓我的程序計算數組中的二進制數並將其存儲為整數值。 這是我到目前為止的代碼,但是當我嘗試將其存儲到2d數組中的空間時,它似乎不起作用。
if (sv1==1)
{
int onesValue=0;
int answer;
v1=p1.charAt(0);
v2=p1.charAt(1);
v3=p1.charAt(2);
v4=p1.charAt(3);
v5=p1.charAt(4);
if (v1==1)
{
onesValue++;
}
if (v2==1)
{
onesValue++;
}
if (v3==1)
{
onesValue++;
}
if (v4==1)
{
onesValue++;
}
if (v4==1)
{
onesValue++;
}
if (v5==1)
{
onesValue++;
}
scoreSheet[0][0] =onesValue;
}
sv1是轉換成雙精度型的字符串,p1是轉換成數組的字符串。如果有人可以幫助我,將不勝感激。
據我了解,我認為這應該算是必需品的出現。
String find="2";
String[] array = {"2", "2", "3", "1", "2"};
Arrays.stream(array)
.collect(Collectors.groupingBy(s -> s))
.forEach((k, v) -> System.out.println(k.equals(find)?k + " - " + v.size()+" times":""));
更新:
如果它是一個int數組,則可以使用以下代碼:
String find=2;
long count = Arrays.stream(array).filter((s)-> s == find).count();
System.out.println("count of "+find+ " is - "+count);
有幫助嗎?
int i[] = {2,5,4,23,7,2,4,2};
int occurnce = 0;
Scanner s = new Scanner(System.in);
System.out.println("Enter the number :");
int number = s.nextInt();
for (int n=0;n<i.length;n++){
if(i[n] == number)
occurnce++;
}
if(occurnce>0)
System.out.println("Number of occurance : " +occurnce);
else
System.out.println("Number doesnt exist");
使用Collections.frequency方法
http://www.tutorialspoint.com/java/util/collections_frequency.htm
Integer arry[] = {2,5,4,23,7,2,4,2};
Map<Integer, Integer> resultMap = new HashMap<Integer, Integer>();
for (int index=0; index < arry.length;index++ ) {
int counter = 1;
Integer valueTobeChecked = arry[index];
if (!resultMap.containsKey(valueTobeChecked)) {
resultMap.put(valueTobeChecked, counter);
} else {
counter = resultMap.get(valueTobeChecked);
resultMap.put(valueTobeChecked, ++counter);
}
}
System.out.println(resultMap);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.