1,字符串次数的统计:

计算同一个人出现在一个地方的次数;

  1. package day08.Demo01;
  2. import java.util.ArrayList;
  3. import java.util.HashMap;
  4. import java.util.Map;
  5. import java.util.Set;
  6. /**
  7. * @author Jztice5
  8. * @date 2022年02月15日 8:56
  9. */
  10. public class Text02 {
  11. //
  12. // 小婷,广州
  13. // 武武,广州
  14. // 武武,深圳
  15. // 武武,东莞
  16. // 小婷,广州
  17. // 小婷,深圳
  18. // 武武,东莞
  19. // 武武,东莞
  20. public static void main(String[] args) {
  21. A a1 = new A("小婷", "广州");
  22. A a2 = new A("武武", "广州");
  23. A a3 = new A("武武", "深圳");
  24. A a4 = new A("武武", "东莞");
  25. A a5 = new A("小婷", "广州");
  26. A a6 = new A("小婷", "深圳");
  27. A a7 = new A("武武", "东莞");
  28. A a8 = new A("武武", "东莞");
  29. ArrayList<A> list = new ArrayList<>();
  30. list.add(a1);
  31. list.add(a2);
  32. list.add(a3);
  33. list.add(a4);
  34. list.add(a5);
  35. list.add(a6);
  36. list.add(a7);
  37. list.add(a8);
  38. HashMap<A, Integer> map1 = new HashMap<>();
  39. for (A a : list) {
  40. if (map1.containsKey(a)){
  41. // Set<Map.Entry<String, Integer>> entrySet = map1.entrySet();
  42. // !!!一定要注意,去重就要重写equals和hashcode
  43. map1.put(a,map1.get(a)+1);
  44. }else {
  45. map1.put(a,1);
  46. }
  47. }
  48. Set<Map.Entry<A, Integer>> entrySet = map1.entrySet();
  49. for (Map.Entry<A, Integer> entry : entrySet) {
  50. A key = entry.getKey();
  51. Integer value = entry.getValue();
  52. System.out.println(key+"\t"+value);
  53. }
  54. }
  55. }
  56. class A{
  57. private String name;
  58. private String address;
  59. public A() {
  60. }
  61. public A(String name, String address) {
  62. this.name = name;
  63. this.address = address;
  64. }
  65. /**
  66. * 获取
  67. * @return name
  68. */
  69. public String getName() {
  70. return name;
  71. }
  72. /**
  73. * 设置
  74. * @param name
  75. */
  76. public void setName(String name) {
  77. this.name = name;
  78. }
  79. /**
  80. * 获取
  81. * @return address
  82. */
  83. public String getAddress() {
  84. return address;
  85. }
  86. /**
  87. * 设置
  88. * @param address
  89. */
  90. public void setAddress(String address) {
  91. this.address = address;
  92. }
  93. public String toString() {
  94. return "A{name = " + name + ", address = " + address + "}";
  95. }
  96. //去重!!!!!!!!!!!!!!!
  97. @Override
  98. public boolean equals(Object o) {
  99. if (this == o) return true;
  100. if (o == null || getClass() != o.getClass()) return false;
  101. A a = (A) o;
  102. if (name != null ? !name.equals(a.name) : a.name != null) return false;
  103. return address != null ? address.equals(a.address) : a.address == null;
  104. }
  105. @Override
  106. public int hashCode() {
  107. int result = name != null ? name.hashCode() : 0;
  108. result = 31 * result + (address != null ? address.hashCode() : 0);
  109. return result;
  110. }
  111. }