定義方法統計集合中指定元素出現的次數,如“a“ 3,“b“ 2,“c“ 1

煙雨彷徨~~Xun發表於2020-11-05

有如下程式碼:
List list = new ArrayList<>();

	list.add("a");
	list.add("a");
	list.add("a");
	list.add("b");
	list.add("b");
	list.add("c");
	list.add("d");
	list.add("d");
	list.add("d");
	list.add("d");
	list.add("d");
	
	System.out.println(frequency(list, "a"));	// 3
	System.out.println(frequency(list, "b"));	// 2
	System.out.println(frequency(list, "c"));	// 1
	System.out.println(frequency(list, "d"));	// 5
	System.out.println(frequency(list, "xxx"));	// 0
(2)定義方法統計集合中指定元素出現的次數,如"a" 3,"b" 2,"c" 1
package zuoye;

import java.util.ArrayList;
import java.util.List;

public class Domo01 {

	public static void main(String[] args) {
		List< String> list = new ArrayList<>();
		list.add("a");
		list.add("a");
		list.add("a");
		list.add("b");
		list.add("b");
		list.add("c");
		list.add("d");
		list.add("d");
		list.add("d");
		
		

		System.out.println(frequency(list,"a"));
		System.out.println(frequency(list,"b"));
		System.out.println(frequency(list,"c"));
		System.out.println(frequency(list,"d"));
		System.out.println(frequency(list,"xxx"));
		
		

		
		
	}

	private static int frequency(List<String> list, String a) {
		int m=0;
		for(int i=0;i<list.size();i++) {
			if(a.equals(list.get(i))) {
				m++;
			}
		}
			
		return m;
	}
}

相關文章