Realize the number of occurrences of the string in the collection

Idea: You can first check the original collection and output it to a new collection, and then use the new collection with the duplicates removed to traverse the original collection, and the double-layer for loop to get the number of repetitions and add it to the new one Output class (this class will be introduced below), after executing a full for loop, add the value and number of times to the set of newly created output classes, and reset num to zero to facilitate the next record. Then print it.

The specific implementation is below

main method

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));
	}

If you want to print the number of occurrences of a string and the corresponding string, you can build a new collection to receive these content, so I wrote a StringTimes class to receive the content, and rewritten the toString method to print it.

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;
	}
}

Method of processing

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;
	}
Like it, like it and collect it!!!

Guess you like

Origin blog.csdn.net/xiaole060901/article/details/107884119