I have a list of objects "Artical" which have 2 attributes articalid and articalVersion as shown below.
enter public class Artical{
public int articalid;
public double articalVersion;
//with getter and setters
}
and now have list having following result
articalid=1098 articalVersion=1.0
articalid=1098 articalVersion=1.1
articalid=1078 articalVersion=1.0
articalid=1078 articalVersion=1.1
articalid=1065 articalVersion=1.0
articalid=1043 articalVersion=1.0
now I want to make list that contain only that objects that have greater version no.(and articalid must not repeat ) like
articalid=1098 articalVersion=1.1
articalid=1078 articalVersion=1.1
articalid=1065 articalVersion=1.0
articalid=1043 articalVersion=1.0
First you sort your List
Collections.sort(articleList, new ArticalComparatorSort());
By using the following comparator:
class ArticalComparatorSort implements Comparator<Artical>
{
@Override
public int compare(Artical a1, Artical a2)
{
if(a1.getArticalid() < a2.getArticalid()){
return -1;
}
else if(a1.getArticalid() > a2.getArticalid()){
return 1;
}
else{ // When both id are equals
return Double.compare(a2.getArticalVersion(), a1.getArticalVersion());
}
}
}
This will sort as:
[1043 : 1.0
, 1065 : 1.0
, 1078 : 1.1
, 1078 : 1.0
, 1098 : 1.1
, 1098 : 1.0
Then use a TreeSet
to remove duplicates
Set<Artical> mySet = new TreeSet<Artical>(new ArticalComparatorSet());
For TreeSet
use the following comperator:
class ArticalComparatorSet implements Comparator<Artical>
{
@Override
public int compare(Artical a1, Artical a2)
{
if(a1.getArticalid() < a2.getArticalid()){
return -1;
}
else if(a1.getArticalid() > a2.getArticalid()){
return 1;
}
else{
return 0;
}
}
}
This will remove duplicates as:
[1043 : 1.0
, 1065 : 1.0
, 1078 : 1.1
, 1098 : 1.1
So you need to add only these three lines of code for removing duplicates:
Collections.sort(articleList, new ArticalComparatorSort());
Set<Artical> mySet = new TreeSet<Artical>(new ArticalComparatorSet());
mySet.addAll(articleList);
And only implement the above comparators
Do like this over an iteration
Map<Integer,Artical> outPuts = new HashMap<Integer,Artical>();
for(Artical artical1 : articals ){
for(Artical artical2 : articals ){
if(artical1.getarticalid() == artical2.getarticalid()){
int retval = Double.compare(artical1.getarticalVersion(), artical2.getarticalVersion());
if(retval > 0) {
if(outPuts.containsKey(artical1.getarticalid())){
outPuts.remove(artical1.getarticalid());
outPuts.add(artical1.getarticalid(),artical1);
}else{
outPuts.add(artical1.getarticalid(),artical1);
}
}
else{
if(outPuts.containsKey(artical1.getarticalid())){
outPuts.remove(artical1.getarticalid());
outPuts.add(artical1.getarticalid(),artical1);
}else{
outPuts.add(artical1.getarticalid(),artical1);
}
}
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.