我有ArrayList<CustomObject> myFinalList = new ArrayList<CustomObject>();
该列表具有列表中每个条目的ojbect属性“NumberOfLikes”。 “NumberOfLikes”是字符串值。
我将这些值派生成一个数组,如下所示: -
ArrayList<String> numberOfLikes = new ArrayList<String>();
for(int j =0; j<myFinalList.size(); j++)
{
String likes = myFinalList.get(j).getNewsLikes();
numberOfLikes.add(likes);
}
numberofLikesArray= numberOfLikes.toArray(new String[numberOfLikes.size()]);
int[] numberofLikesArrayInt = new int[numberofLikesArray.length];
for (int n = 0; n < numberofLikesArray.length; n++)
{
numberofLikesArrayInt[n] = Integer.parseInt(numberofLikesArray[n]);
}
Arrays.sort(numberofLikesArrayInt);
ArrayList<Integer> intAarrylistlikes = new ArrayList<Integer>();
for (int i = 0; i < numberofLikesArrayInt.length; i++)
{
intAarrylistlikes.add(numberofLikesArrayInt[i]);
}
Collections.reverse(intAarrylistlikes);
numberofLikesArrayInt = convertIntegers(intAarrylistlikes);
numberofLikesArray = Arrays.toString(numberofLikesArrayInt).split("[\\[\\]]")[1].split(", ");
for (int i = 0; i < numberofLikesArray.length; i++)
{
companyNewsList = Lists.newArrayList(Collections2.filter(myFinalList, new ArticleFilter2(numberofLikesArray[i])));
}
ArticleFilter2.java
public class ArticleFilter2 implements Predicate<News>
{
private final Pattern pattern;
public ArticleFilter2(final String regex)
{
pattern = Pattern.compile(regex);
}
@Override
public boolean apply(final CustomObject input)
{
return pattern.matcher(input.getLikes()).find();
}
}
现在这个数组按降序排列“NumberOfLikes”。现在我想创建另一个ArrayList,根据这些值对“MyFinalList”进行排序,即: - 具有最大喜欢的项目应首先出现。
我该怎么做?
答案 0 :(得分:1)
这要求您使用自定义类Comparator
。
http://docs.oracle.com/javase/7/docs/api/java/util/Comparator.html
创建一个实现Comparator的新类并实现此方法:
public class YourComparator<CustomClass> implements Comparator{
@Override
public int compare ( CustomClass obj1, CustomClass obj2 ) {
return (int) (obj1.getYourProperty() - obj2.getYourProperty());
}
}
使用它:
Collections.sort(MyFinalList, new YourComparator());