@SpringBootTest
class DemoApplicationTests {
@Test
void contextLoads() {
List<User> resource = Lists.newArrayList();
User user = new User(1L,"shihf","123456");
User user2 = new User(1L,"shihf2","123456");
User user3 = new User(1L,"shihf2","1234567");
User user4 = new User(1L,"shihf","123456");
resource.add(user);
resource.add(user2);
resource.add(user3);
resource.add(user4);
//整体去重
// resource.stream().distinct().collect(Collectors.toList()).size();//需要equals和hashcode方法
// System.out.println(resource.stream().distinct().collect(Collectors.toList()).size());
// HashSet<User> userHashSet = Sets.newHashSet(resource);
// System.out.println(userHashSet.size());
//单个字段去重
// List<User> collect = resource.stream().collect(collectingAndThen(
// toCollection(() -> new TreeSet<>(comparingLong(User::getUserId))), ArrayList::new));
// System.out.println(collect.size());
HashSet<User> userHashSet = Sets.newHashSet(resource);
System.out.println(userHashSet.size());
/** 生成指定的方法
* // @Override
* // public boolean equals(Object o) {
* // if (this == o) return true;
* //
* // if (o == null || getClass() != o.getClass()) return false;
* //
* // User user = (User) o;
* //
* // return new org.apache.commons.lang3.builder.EqualsBuilder()
* // .append(userId, user.userId)
* // .isEquals();
* // }
* //
* // @Override
* // public int hashCode() {
* // return new org.apache.commons.lang3.builder.HashCodeBuilder(17, 37)
* // .append(userId)
* // .toHashCode();
* // }
*/
//多字段去重 建议生成指定的方法
}
}
@AllArgsConstructor
@NoArgsConstructor
@Setter
@Getter
@ToString
@Accessors(chain = true)
//@EqualsAndHashCode
class User{
private Long userId;
private String userName;
private String userPwd;
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
//
// if (o == null || getClass() != o.getClass()) return false;
//
// User user = (User) o;
//
// return new org.apache.commons.lang3.builder.EqualsBuilder()
// .append(userId, user.userId)
// .isEquals();
// }
//
// @Override
// public int hashCode() {
// return new org.apache.commons.lang3.builder.HashCodeBuilder(17, 37)
// .append(userId)
// .toHashCode();
// }
}
集合去重方法
最新推荐文章于 2023-11-30 18:52:55 发布