diff --git a/src/main/java/com/github/hcsp/collection/Main.java b/src/main/java/com/github/hcsp/collection/Main.java index ae0f842..2c27e95 100644 --- a/src/main/java/com/github/hcsp/collection/Main.java +++ b/src/main/java/com/github/hcsp/collection/Main.java @@ -1,12 +1,16 @@ package com.github.hcsp.collection; -import java.util.Arrays; -import java.util.List; -import java.util.Set; +import java.util.*; +import java.util.stream.Collectors; public class Main { // 请编写一个方法,获得a和b集合中的公共元素。 - public static Set commonElementsIn(List a, List b) {} + public static Set commonElementsIn(List a, List b) { + ArrayList personsOne = new ArrayList<>(a); + ArrayList personsTwo = new ArrayList<>(b); + personsOne.retainAll(personsTwo); + return new HashSet<>(personsOne); + } // Person类,如果两个Person对象的name相等,则认为这两个对象相等。 public static class Person { @@ -23,11 +27,27 @@ public String getName() { public void setName(String name) { this.name = name; } + + @Override + public boolean equals(Object obj) { + if(obj instanceof Person) { + Person person = (Person) obj; + return this.getName().equals(person.getName()); + } + return false; + } + + @Override + public int hashCode() { + return name.hashCode(); + } } public static void main(String[] args) { List list1 = Arrays.asList(new Person("张学友"), new Person("周杰伦")); List list2 = Arrays.asList(new Person("周润发"), new Person("周杰伦")); + System.out.println(list1); + System.out.println(list2); System.out.println(commonElementsIn(list1, list2)); } } diff --git a/src/test/java/com/github/hcsp/collection/MainTest.java b/src/test/java/com/github/hcsp/collection/MainTest.java index 1697f32..e6e992a 100644 --- a/src/test/java/com/github/hcsp/collection/MainTest.java +++ b/src/test/java/com/github/hcsp/collection/MainTest.java @@ -3,6 +3,7 @@ import java.util.Arrays; import java.util.HashSet; import java.util.List; + import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test;