1,字符串次数的统计:
计算同一个人出现在一个地方的次数;
package day08.Demo01;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
/**
* @author Jztice5
* @date 2022年02月15日 8:56
*/
public class Text02 {
//
// 小婷,广州
// 武武,广州
// 武武,深圳
// 武武,东莞
// 小婷,广州
// 小婷,深圳
// 武武,东莞
// 武武,东莞
public static void main(String[] args) {
A a1 = new A("小婷", "广州");
A a2 = new A("武武", "广州");
A a3 = new A("武武", "深圳");
A a4 = new A("武武", "东莞");
A a5 = new A("小婷", "广州");
A a6 = new A("小婷", "深圳");
A a7 = new A("武武", "东莞");
A a8 = new A("武武", "东莞");
ArrayList<A> list = new ArrayList<>();
list.add(a1);
list.add(a2);
list.add(a3);
list.add(a4);
list.add(a5);
list.add(a6);
list.add(a7);
list.add(a8);
HashMap<A, Integer> map1 = new HashMap<>();
for (A a : list) {
if (map1.containsKey(a)){
// Set<Map.Entry<String, Integer>> entrySet = map1.entrySet();
// !!!一定要注意,去重就要重写equals和hashcode
map1.put(a,map1.get(a)+1);
}else {
map1.put(a,1);
}
}
Set<Map.Entry<A, Integer>> entrySet = map1.entrySet();
for (Map.Entry<A, Integer> entry : entrySet) {
A key = entry.getKey();
Integer value = entry.getValue();
System.out.println(key+"\t"+value);
}
}
}
class A{
private String name;
private String address;
public A() {
}
public A(String name, String address) {
this.name = name;
this.address = address;
}
/**
* 获取
* @return name
*/
public String getName() {
return name;
}
/**
* 设置
* @param name
*/
public void setName(String name) {
this.name = name;
}
/**
* 获取
* @return address
*/
public String getAddress() {
return address;
}
/**
* 设置
* @param address
*/
public void setAddress(String address) {
this.address = address;
}
public String toString() {
return "A{name = " + name + ", address = " + address + "}";
}
//去重!!!!!!!!!!!!!!!
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
A a = (A) o;
if (name != null ? !name.equals(a.name) : a.name != null) return false;
return address != null ? address.equals(a.address) : a.address == null;
}
@Override
public int hashCode() {
int result = name != null ? name.hashCode() : 0;
result = 31 * result + (address != null ? address.hashCode() : 0);
return result;
}
}