diff --git a/src/main/java/com/github/hcsp/collection/Main.java b/src/main/java/com/github/hcsp/collection/Main.java index ae0f842..e452a91 100644 --- a/src/main/java/com/github/hcsp/collection/Main.java +++ b/src/main/java/com/github/hcsp/collection/Main.java @@ -1,12 +1,32 @@ package com.github.hcsp.collection; -import java.util.Arrays; import java.util.List; import java.util.Set; +import java.util.Map; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Objects; +import java.util.Arrays; public class Main { // 请编写一个方法,获得a和b集合中的公共元素。 - public static Set commonElementsIn(List a, List b) {} + public static Set commonElementsIn(List a, List b) { + Set result = new HashSet<>(); + Map hashMap = new HashMap<>(a.size() + b.size()); + for (Person p : a) { + hashMap.put(p, hashMap.getOrDefault(p, 0) + 1); + } + for (Person p : b) { + hashMap.put(p, hashMap.getOrDefault(p, 0) + 1); + } + hashMap.forEach((key, value) -> { + if (value >= 2) { + result.add(key); + } + }); + return result; + } + // Person类,如果两个Person对象的name相等,则认为这两个对象相等。 public static class Person { @@ -23,6 +43,17 @@ public String getName() { public void setName(String name) { this.name = name; } + + @Override + public boolean equals(Object obj) { + return Objects.equals(name, ((Person) obj).getName()); + } + + @Override + public int hashCode() { + return name.hashCode(); + } + } public static void main(String[] args) {