用Java写算法技巧(1)去掉List中的重复对象
2012-12-26 14:40
519 查看
最近写聚类算法,输入的数据集是一些二维点坐标,我的数据有很多重复的点,需要做一下预处理,去掉这些重复点。百度和谷歌一阵后,找到了解决方法,希望对阅读本文的人有帮助。
1、 数据文件points.txt,文件内容和格式如下:
2、添加一个Point对象,用来保存点数据。最重要的是要实现equal方法,这个在去除重复对象时会用到。
public class Point {
private double x;
private double y;
public double getX() {
return x;
}
public void setX(double x) {
this.x = x;
}
public double getY() {
return y;
}
public void setY(double y) {
this.y = y;
}
public Point(){
x=0;
y=0;
}
public Point(double x,double y){
this.x=x;
this.y=y;
}
public Point(String str){
String[] p=str.split(",");
this.x=Double.valueOf(p[0]);
this.y=Double.valueOf(p[1]);
}
public String print(){
return "<"+this.x+","+this.y+">";
}
//这个方法是关键
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (this == obj) {
return true;
}
Point other = (Point) obj;
if (this.getX() == other.getX() && this.getY() == other.getY()) {
return true;
}
return false;
}
}
3、从文件points.txt中读取点信息,然后保存在List对象中。
1、 数据文件points.txt,文件内容和格式如下:
2、添加一个Point对象,用来保存点数据。最重要的是要实现equal方法,这个在去除重复对象时会用到。
public class Point {
private double x;
private double y;
public double getX() {
return x;
}
public void setX(double x) {
this.x = x;
}
public double getY() {
return y;
}
public void setY(double y) {
this.y = y;
}
public Point(){
x=0;
y=0;
}
public Point(double x,double y){
this.x=x;
this.y=y;
}
public Point(String str){
String[] p=str.split(",");
this.x=Double.valueOf(p[0]);
this.y=Double.valueOf(p[1]);
}
public String print(){
return "<"+this.x+","+this.y+">";
}
//这个方法是关键
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (this == obj) {
return true;
}
Point other = (Point) obj;
if (this.getX() == other.getX() && this.getY() == other.getY()) {
return true;
}
return false;
}
}
3、从文件points.txt中读取点信息,然后保存在List对象中。
public List<Point> getPointsList() throws IOException{ List<Point> lst=new ArrayList<Point>(); String txtPath="points.txt"; BufferedReader br=new BufferedReader(new FileReader(txtPath)); String str=""; while((str=br.readLine())!=null && str!=""){ lst.add(new Point(str)); } br.close(); //过滤重复的Point对象 List<Point> list = new ArrayList<Point>(); for (Object o:lst) { if (!list.contains(o)) { list.add((Point)o); } } return list; }
相关文章推荐
- Java List<Object>去掉重复对象-java8
- Java判断一个值,或者对象是否存在list集合中和去掉list集合中重复的元素
- Java List<Object>去掉重复对象-java8
- Java List<Object>去掉重复对象-java8
- java中如何去掉list中重复的对象
- Java List<Object>去掉重复对象
- Java List<Object>去掉重复对象-java8
- List去掉重复对象
- 去掉list中重复元素并合并相同对象
- java判断List<T>对象是否唯一、去重复
- [Java] Java中List 去掉重复的值,并保持原先List顺序
- Java 之List根据对象字段名去重复
- java去掉list中的重复元素
- java中两个list去掉重复元素
- java8 lambda 统计list中对象的重复次数
- Java中List 去掉重复的值,并保持原先List顺序
- (Java 功能代码)java去除List中重复数据之Object对象
- JAVA-去掉LIST中重复值
- 用HashSet去掉List中重复对象的时候要注意
- java计算list集合中重复对象的次数及for循环内外创建对象