在日常的学习和工作中会遇到大量数据重复的情况,大部分可能会选择进行sql去重,其实还有一种方法就是利用Set集合进行去重。Set集合是无序的,可以利用这一特性对数据进行去重。
- 实体类:
public class Message {
public final int sequence;
public final String text;
//鼠标右键选择Generate... 可以选择生成构造方法,toString方法,equals()方法,hashCode()方法
public Message(int s, String t) {
this.sequence = s;
this.text = t;
}
//快捷键Alt+insert 而可以选择生成构造方法,toString方法,equals()方法,hashCode()方法
@Override
public String toString() {
return "Message{" +
"sequence=" + sequence +
", text='" + text + '\'' +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Message message = (Message) o;
return sequence == message.sequence && Objects.equals(text, message.text);
}
@Override
public int hashCode() {
return Objects.hash(sequence, text);
}
}
2.业务处理类:
@Service
public class SetDeService {
public void test() {
List<Message> messageList = new ArrayList<>();
messageList.add(new Message(1, "Hello!"));
messageList.add(new Message(1, "Hello!"));
messageList.add(new Message(2, "吃饭了吗?"));
messageList.add(new Message(2, "吃饭了吗?"));
messageList.add(new Message(3, "buy!"));
List<Message> process = process(messageList);
for (Message message : process) {
System.out.println(message.text);
}
}
private List<Message> process(List<Message> received) {
Set<Message> set = new HashSet<>();
List<Message> list = new ArrayList<>();
for (Message message : received) {
set.add(message);
}
for (Message message : set) {
list.add(message);
}
return list;
}
}
数据展示:
@RestController
@RequestMapping("/SetDe")
public class SetDeController {
@Lazy
@Resource
SetDeService service;
@RequestMapping("/test")
public String test() {
try {
service.test();
return "成功";
} catch (Exception e) {
e.printStackTrace();
return "失败";
}
}
}
结果: