how to sort the Vector containing objects using Blackberry API - sorting

I want to sort a vector which contains Object of following fields
public class CategoryListing {
String company_id;
String company_name;
double distance;
//setters and getters here
}
I populated the vector from webservice, now I want to sort that vector by distance, means I want to show nearest one. How can I sort the vector which contains objects?

None of the other answers are going to work for you on Blackberry as it doesn't support Generics. Blackberry uses older version of Java. Try the following code. It uses SimpleSortingVector
SimpleSortingVector sortVector = new SimpleSortingVector();
sortVector.setSortComparator(new Comparator() {
public int compare(Object o1, Object o2) {
CategoryListing o1C = (CategoryListing)o1;
CategoryListing o2C = (CategoryListing)o2;
return Double.toString((o1C.distance)).compareTo(Double.toString(o2C.distance));
}
});
//when you add elements to this vector, it is automatically sorted by distance
sortVector.addElement(new CategoryListing());

You can use Comparator.
Define a comparator which will sort on distance like below
public class DistanceComparator implements Comparator {
public int compare(Object o1, Object o2) {
return Double.valueOf(((CategoryListing) o1).distance)
.compareTo(((CategoryListing) o2).distance);// use getters
}
}
Sort vector using below sort method. Note As Arrays are present from 1.2 It is also present for blackberry.
public static void sort(Vector vector,Comparator comparator) {
Object[] array = new Object[vector.size()];
vector.copyInto(array);
Arrays.sort(array,comparator);
int i = 0;
Enumeration enumumeration = vector.elements();
while (enumumeration.hasMoreElements()) {
enumumeration.nextElement();
vector.insertElementAt(array[i++], i);
}
}

Related

Comparable class with a List<String> field

I have a simple class which stores an integer and a list of Strings.
As I want to use this class in a TreeSet<>, the one must be Comparable.
But when trying to use the Java 8 Comparator class, I cannot compare my inner list.
I have the following error:
Bad return type in method reference: cannot convert java.util.List to U
I think there is a very simple way to do that but I could not find it out.
How to do that?
public class MyClass implements Comparable<MyClass> {
private final int someInt;
private final List<String> someStrings;
public MyClass (List<String> someStrings, int someInt) {
this.someInt = someInt;
this.someStrings = new ArrayList<>(someStrings);
}
#Override
public int compareTo(MyClass other) {
return
Comparator.comparing(MyClass::getSomeInt)
.thenComparing(MyClass::getSomeStrings) // Error here
.compare(this, other);
}
public int getSomeInt() {
return someInt;
}
public List<String> getSomeStrings() {
return someStrings;
}
}
Edit 1
I just want the String list to be compared in the simplest way (using implicitly String.compareTo()).
Note that I do now want to sort my List<String> but I want it to be Comparable so that MyClass is also comparable and finally, I can insert MyClass instances into a TreeSet<MyClass>.
A also saw in the JavaDoc the following:
java.util.Comparator<T> public Comparator<T>
thenComparing(#NotNull Comparator<? super T> other)
For example, to sort a collection of String based on the length and then case-insensitive natural ordering, the comparator can be composed using following code,
Comparator<String> cmp = Comparator.comparingInt(String::length)
.thenComparing(String.CASE_INSENSITIVE_ORDER);
It seems to be an clue but I don't know how to apply it to this simple example.
Edit 2
Let's say I want my List<String> to be sorted the following way:
First check: List.size() (the shorter is less than the larger one);
Second check if sizes match: comparing one by one each element of both Lists until finding one where the String.compareTo method returns 1 or -1.
How to do that with lambdas in a my compareTo method?
Edit 3
This does not duplicates this question because I want to know how to build a comparator of a class which contains a List<String> with Java 8 chaining Comparable calls.
So to compare the list, first you check the length, then you compare each item with same indexes in both list one by one right?
(That is [a, b, c] < [b, a, c])
Make a custom comparator for list return join of your list string:
Comparator<List<String>> listComparator = (l1, l2) -> {
if (l1.size() != l2.size()) {
return l1.size() - l2.size();
}
for (int i = 0; i < l1.size(); i++) {
int strCmp = l1.get(i).compareTo(l2.get(i));
if (strCmp != 0) {
return strCmp;
}
}
return 0; // Two list equals
};
Then you can compare using that custom comparator:
#Override
public int compareTo(MyClass other) {
return Comparator.comparing(MyClass::getSomeInt)
.thenComparing(Comparator.comparing(MyClass:: getSomeStrings , listComparator))
.compare(this, other);
}
If you want [a, b, c] = [b, a, c], then you have to sort those list first before comparing:
public String getSomeStringsJoined() {
return getSomeStrings().stream().sort(Comparator.naturalOrder()).collect(Collectors.joining());
}

Better version of Compare Extension for Linq

I need to get differences between two IEnumerable. I wrote extension method for it. But as you can see, it has performance penalties. Anyone can write better version of it?
EDIT
After first response, I understand that I could not explain well. I'm visiting both arrays three times. This is performance penalty. It must be a single shot.
PS: Both is optional :)
public static class LinqExtensions
{
public static ComparisonResult<T> Compare<T>(this IEnumerable<T> source, IEnumerable<T> target)
{
// Looping three times is performance penalty!
var res = new ComparisonResult<T>
{
OnlySource = source.Except(target),
OnlyTarget = target.Except(source),
Both = source.Intersect(target)
};
return res;
}
}
public class ComparisonResult<T>
{
public IEnumerable<T> OnlySource { get; set; }
public IEnumerable<T> OnlyTarget { get; set; }
public IEnumerable<T> Both { get; set; }
}
Dependig on the use-case, this might be more efficient:
public static ComparisonResult<T> Compare<T>(this IEnumerable<T> source, IEnumerable<T> target)
{
var both = source.Intersect(target).ToArray();
if (both.Any())
{
return new ComparisonResult<T>
{
OnlySource = source.Except(both),
OnlyTarget = target.Except(both),
Both = both
};
}
else
{
return new ComparisonResult<T>
{
OnlySource = source,
OnlyTarget = target,
Both = both
};
}
}
You're looking for an efficient full outer join.
Insert all items into a Dictionary<TKey, Tuple<TLeft, TRight>>. If a given key is not present, add it to the dictionary. If it is present, update the value. If the "left member" is set, this means that the item is present in the left source collection (you call it source). The opposite is true for the right member. You can do that using a single pass over both collections.
After that, you iterate over all values of this dictionary and output the respective items into one of three collections, or you just return it as an IEnumerable<Tuple<TLeft, TRight>> which saves the need for result collections.

Keyword Search for ListField in Blackberry

I am creating a ListField. in each row of I am adding a image and 3 labelfield.
Can any one tell me how to create a keywordfilterField for this...
Thanks in advance
I am new to blackberry.
Little code will help me alot
This is my code for creating a custom list
class CustomListField extends ListField implements ListFieldCallback
{
String type;
int DISPLAY_WIDTH = Display.getWidth();
int DISPLAY_HEIGHT = Display.getHeight();
Vector mItems = new Vector();
Vector mine = new Vector();
Vector three= new Vector();
// SizedVFM mListManager = new SizedVFM(DISPLAY_WIDTH, DISPLAY_HEIGHT - 40);
Bitmap searchresult = Bitmap.getBitmapResource("res/searchresult.png");
HorizontalFieldManager hfManager;
Bitmap image ,image1;
int z = this.getRowHeight();
CustomListField(String text1,String text2,String type)
{
for (int i = 1; i < 31; i++)
{
mItems.addElement(text1 +String.valueOf(i));
mine.addElement(" "+text2);
three.addElement("31");
}
this.type=type;
this.setRowHeight((2*z));
this.setCallback(this);
this.setSize(20);
//mListManager.add(mListField);
//add(mListManager);
}
public void drawListRow(ListField field, Graphics g, int i, int y, int w)
{
// Draw the text.
image = Bitmap.getBitmapResource("res/searchresult.png");
String text = (String) get(field, i);
String mytext = (String)mine.elementAt(i);
String urtext=(String)three.elementAt(i);
g.drawBitmap(0, y, image.getWidth(),image.getHeight(), image, 0, 0);
g.drawText(text, image.getWidth(), y, 0, w);
g.setColor(Color.GRAY);
g.drawText(mytext, image.getWidth(), y+getFont().getHeight(), 0, w);
g.drawText(urtext,Graphics.getScreenWidth()*7/8,y,0,w);
if (i != 0)
{
g.drawLine(0, y, w, y);
}
}
public Object get(ListField listField, int index)
{
return mItems.elementAt(index);
}
public int getPreferredWidth(ListField listField)
{
return DISPLAY_WIDTH;
}
public int indexOfList(ListField listField, String prefix, int start)
{
return 0;
}
protected boolean touchEvent(TouchEvent message)
{
// If click, process Field changed
if ( message.getEvent() == TouchEvent.CLICK )
{
if(type.equals("Stops"))
UiApplication.getUiApplication().pushScreen(new SearchScreen("Services"));
else if(type.equals("Services"))
UiApplication.getUiApplication().pushScreen(new SearchScreen("Stops"));
return true;
}
return super.touchEvent(message);
}
}
The problem with KeywordFilterField is that it uses internally its own ListField, so I think it is going to be difficult to customize. If you wanted to use it as it is provided, you'll have to use it as follows:
//KeywordFilterField contains a ListField to display and a search edit field to type in the words
KeywordFilterField keywordFilterField = new KeywordFilterField();
//Instantiate the sorted collection:
CustomList cl = new CustomList(mItems);
//Pass the custom collection
keywordFilterField.setSourceList(cl, cl);
//Now you have to add two fields: first the list itself
myManager.add(keywordFilterField);
//And the search field, probably you'd want it at top:
myScreen.setTitle(keywordFilterField.getKeywordField());
You'll have to implement a custom sortable collection to hold the items you wan't to display:
class CustomList extends SortedReadableList implements KeywordProvider {
//In constructor, call super constructor with a comparator of <yourClass>
public CustomList(Vector elements)
{
super(new <yourClass>Comparator()); //pass comparator to sort
loadFrom(elements.elements());
}
//Interface implementation
public String[] getKeywords( Object element )
{
if(element instanceof <yourClass> )
{
return StringUtilities.stringToWords(element.toString());
}
return null;
}
void addElement(Object element)
{
doAdd(element);
}
//...
}
You have a full demo available inside the JDE samples folder. It is called keywordfilterdemo.
To use a custom list like the one you posted, you'll probably have to code a lot of stuff, like a custom EditField to type in the keywords receiving events on every typed character, linked to a search on a sortered collection (maybe you could use a SortedReadableList for this) which will select in your ListField the first search result returned by this collection.

Sort Vector of objects in Scala

How can I sort a Vector of my objects in Scala? Is there some library sorting routines or do I have to write my own?
I have a class:
class Data2D(var x:Int, var y:Int)
and I am passing a vector of these to my function:
private def foo(data: Vector[Data2D]): Int = {
data:Vector sortedOnX = // ??
}
how can I sort the vector, based on the x-values of the Data2D objects?
In java I do:
Collections.sort(data, XComparator.INSTANCE);
where XComparator is:
enum XComparator implements Comparator<Data2D> {
INSTANCE;
#Override
public int compare(Data2D o1, Data2D o2) {
if (o1.getX() <= o2.getX()) {
return -1;
} else {
return 1;
}
}
}
private def foo(data: Vector[Data2D]): Int = data.sortBy(_.x)
See also the methods sortWith and sorted, as well as the methods provided by the Ordering object.

Using Distinct with LINQ and Objects [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 months ago.
The community reviewed whether to reopen this question 9 months ago and left it closed:
Original close reason(s) were not resolved
Improve this question
Until recently, I was using a Distinct in LINQ to select a distinct category (an enum) from a table. This was working fine.
I now need to have it distinct on a class containing a category and country (both enums). The Distinct isn't working now.
What am I doing wrong?
I believe this post explains your problem:
http://blog.jordanterrell.com/post/LINQ-Distinct()-does-not-work-as-expected.aspx
The content of the above link can be summed up by saying that the Distinct() method can be replaced by doing the following.
var distinctItems = items
.GroupBy(x => x.PropertyToCompare)
.Select(x => x.First());
try an IQualityComparer
public class MyObjEqualityComparer : IEqualityComparer<MyObj>
{
public bool Equals(MyObj x, MyObj y)
{
return x.Category.Equals(y.Category) &&
x.Country.Equals(y.Country);
}
public int GetHashCode(MyObj obj)
{
return obj.GetHashCode();
}
}
then use here
var comparer = new MyObjEqualityComparer();
myObjs.Where(m => m.SomeProperty == "whatever").Distinct(comparer);
You're not doing it wrong, it is just the bad implementation of .Distinct() in the .NET Framework.
One way to fix it is already shown in the other answers, but there is also a shorter solution available, which has the advantage that you can use it as an extension method easily everywhere without having to tweak the object's hash values.
Take a look at this:
**Usage:**
var myQuery=(from x in Customers select x).MyDistinct(d => d.CustomerID);
Note: This example uses a database query, but it does also work with an enumerable object list.
Declaration of MyDistinct:
public static class Extensions
{
public static IEnumerable<T> MyDistinct<T, V>(this IEnumerable<T> query,
Func<T, V> f)
{
return query.GroupBy(f).Select(x=>x.First());
}
}
Or if you want it shorter, this is the same as above, but as "one-liner":
public static IEnumerable<T> MyDistinct<T, V>(this IEnumerable<T> query, Func<T, V> f)
=> query.GroupBy(f).Select(x => x.First());
And it works for everything, objects as well as entities. If required, you can create a second overloaded extension method for IQueryable<T> by just replacing the return type and first parameter type in the example I've given above.
Test data:
You can try it out with this test data:
List<A> GetData()
=> new List<A>()
{
new A() { X="1", Y="2" }, new A() { X="1", Y="2" },
new A() { X="2", Y="3" }, new A() { X="2", Y="3" },
new A() { X="1", Y="3" }, new A() { X="1", Y="3" },
};
class A
{
public string X;
public string Y;
}
Example:
void Main()
{
// returns duplicate rows:
GetData().Distinct().Dump();
// Gets distinct rows by i.X
GetData().MyDistinct(i => i.X).Dump();
}
For explanation, take a look at other answers. I'm just providing one way to handle this issue.
You might like this:
public class LambdaComparer<T>:IEqualityComparer<T>{
private readonly Func<T,T,bool> _comparer;
private readonly Func<T,int> _hash;
public LambdaComparer(Func<T,T,bool> comparer):
this(comparer,o=>0) {}
public LambdaComparer(Func<T,T,bool> comparer,Func<T,int> hash){
if(comparer==null) throw new ArgumentNullException("comparer");
if(hash==null) throw new ArgumentNullException("hash");
_comparer=comparer;
_hash=hash;
}
public bool Equals(T x,T y){
return _comparer(x,y);
}
public int GetHashCode(T obj){
return _hash(obj);
}
}
Usage:
public void Foo{
public string Fizz{get;set;}
public BarEnum Bar{get;set;}
}
public enum BarEnum {One,Two,Three}
var lst=new List<Foo>();
lst.Distinct(new LambdaComparer<Foo>(
(x1,x2)=>x1.Fizz==x2.Fizz&&
x1.Bar==x2.Bar));
You can even wrap it around to avoid writing noisy new LambdaComparer<T>(...) thing:
public static class EnumerableExtensions{
public static IEnumerable<T> SmartDistinct<T>
(this IEnumerable<T> lst, Func<T, T, bool> pred){
return lst.Distinct(new LambdaComparer<T>(pred));
}
}
Usage:
lst.SmartDistinct((x1,x2)=>x1.Fizz==x2.Fizz&&x1.Bar==x2.Bar);
NB: works reliably only for Linq2Objects
I know this is an old question, but I am not satisfied with any of the answers. I took time to figure this out for myself and I wanted to share my findings.
First it is important to read and understand these two things:
IEqualityComparer
EqualityComparer
Long story short in order to make the .Distinct() extension understand how to determine equality of your object - you must define a "EqualityComparer" for your object T. When you read the Microsoft docs it literally states:
We recommend that you derive from the EqualityComparer class
instead of implementing the IEqualityComparer interface...
That is how you determine what to use, because it had been decided for you already.
For the .Distinct() extension to work successfully you must ensure that your objects can be compared accurately. In the case of .Distinct() the GetHashCode() method is what really matters.
You can test this out for yourself by writing a GetHashCode() implementation that just returns the current Hash Code of the object being passed in and you will see the results are bad because this value changes on each run. That makes your objects too unique which is why it is important to actually write a proper implementation of this method.
Below is an exact copy of the code sample from IEqualityComparer<T>'s page with test data, small modification to the GetHashCode() method and comments to demonstrate the point.
//Did this in LinqPad
void Main()
{
var lst = new List<Box>
{
new Box(1, 1, 1),
new Box(1, 1, 1),
new Box(1, 1, 1),
new Box(1, 1, 1),
new Box(1, 1, 1)
};
//Demonstration that the hash code for each object is fairly
//random and won't help you for getting a distinct list
lst.ForEach(x => Console.WriteLine(x.GetHashCode()));
//Demonstration that if your EqualityComparer is setup correctly
//then you will get a distinct list
lst = lst
.Distinct(new BoxEqualityComparer())
.ToList();
lst.Dump();
}
public class Box
{
public Box(int h, int l, int w)
{
this.Height = h;
this.Length = l;
this.Width = w;
}
public int Height { get; set; }
public int Length { get; set; }
public int Width { get; set; }
public override String ToString()
{
return String.Format("({0}, {1}, {2})", Height, Length, Width);
}
}
public class BoxEqualityComparer
: EqualityComparer<Box>
{
public override bool Equals(Box b1, Box b2)
{
if (b2 == null && b1 == null)
return true;
else if (b1 == null || b2 == null)
return false;
else if (b1.Height == b2.Height && b1.Length == b2.Length
&& b1.Width == b2.Width)
return true;
else
return false;
}
public override int GetHashCode(Box bx)
{
#region This works
//In this example each component of the box object are being XOR'd together
int hCode = bx.Height ^ bx.Length ^ bx.Width;
//The hashcode of an integer, is that same integer
return hCode.GetHashCode();
#endregion
#region This won't work
//Comment the above lines and uncomment this line below if you want to see Distinct() not work
//return bx.GetHashCode();
#endregion
}
}

Resources