컬렉션에서 문자열의 발생 횟수를 인식하십시오.

아이디어 : 먼저 원본 컬렉션을 확인하고 새 컬렉션으로 출력 한 다음, 복제물이 제거 된 새 컬렉션을 사용하여 원본 컬렉션을 탐색하고 이중 레이어 for 루프를 사용하여 반복 횟수를 가져 와서 추가 할 수 있습니다. 새로운 하나의 Output 클래스 (이 클래스는 아래에 소개됨), 전체 for 루프를 실행 한 후 새로 생성 된 출력 클래스 세트에 값과 횟수를 추가하고 다음 레코드를 용이하게하기 위해 num을 0으로 재설정합니다. 그것.

구체적인 구현은 다음과 같습니다.

주요 방법

public class StatisticsRepeatString {
    
    
	public static void main(String[] args) {
    
    
		ArrayList<String> sList = new ArrayList<String>();
		sList.add("nice!");
		sList.add("beautiful!");
		sList.add("nice!");
		sList.add("beautiful!");
		sList.add("nice!");
		sList.add("hello!");
		sList.add("hi!");
		sList.add("gun!");
		sList.add("fuck!");
		sList.add("fuck!");
		sList.add("gun!");
		sList.add("hello!");
		sList.add("fuck!");
		sList.add("nice!");
		
		System.out.println(repeatString(sList));
	}

문자열의 발생 횟수와 해당 문자열을 인쇄하려면 이러한 콘텐츠를받을 새 컬렉션을 만들 수 있으므로 콘텐츠를받을 수있는 StringTimes 클래스를 작성하고이를 인쇄하도록 toString 메서드를 다시 작성했습니다.

public class StringTimes {
    
    
	private String str;
	private int num;
	public StringTimes(String str, int num) {
    
    
		super();
		this.str = str;
		this.num = num;
	}
	@Override
	public String toString() {
    
    
		return "[str=" + str + ", num=" + num + "]";
	}
	public String getStr() {
    
    
		return str;
	}
	public void setStr(String str) {
    
    
		this.str = str;
	}
	public int getNum() {
    
    
		return num;
	}
	public void setNum(int num) {
    
    
		this.num = num;
	}
}

처리 방법

public static ArrayList<StringTimes> repeatString(ArrayList<String> str1){
    
    
		ArrayList<StringTimes> str4 =new ArrayList<StringTimes>();
		int num = 0;
		
		ArrayList<String> str2 =new ArrayList<String>();
		for (int i = 0; i < str1.size(); i++ ) {
    
    
			String str3 = str1.get(i);
			if(!str2.contains(str3)) {
    
    
				str2.add(str3);
			}
		}
		for (int i = 0; i < str2.size(); i++) {
    
    
			for (int j = 0; j < str1.size(); j++) {
    
    
				if(str2.get(i).equals(str1.get(j))) {
    
    
					num++;
				}
			}
			str4.add(new StringTimes(str2.get(i),num));
			num = 0;
		}
		return str4;
	}
좋아요 좋아요 수집하세요 !!!

추천

출처blog.csdn.net/xiaole060901/article/details/107884119