2

I need to sort the list in java as below:

List contains collection of objects like this,

List list1 = {obj1, obj2,obj3,.....};

I need the final list which has "lowest value" and "repetition of name should avoid".

Ex:

List list1 = {[Nellai,10],[Gujarath,10],[Delhi,30],[Nellai,5],[Gujarath,15],[Delhi,20]}

After Sorting , I need the list like this :

List list1 = {[Nellai,5],[Gujarath,10],[Delhi,20]};

I have 2 Delhi (30,20) in my list. But I need only one Delhi which has lowest fare (20).

How to do that it in java?

Gnaniyar Zubair

2
  • Do you have to keep the order of your elements? (i.e.: must Nellai be before Gujarath in the result?) Commented Dec 1, 2010 at 12:13
  • no it is dynamically added. order may change Commented Dec 1, 2010 at 12:19

5 Answers 5

4

If order doesn't matter, a solution is to use a Map[String, Integer], add an entry each time you find a new town, update the value each time the stored value is less than the stored one and then zip all the pairs into a list.

Sign up to request clarification or add additional context in comments.

Comments

1

Almost the same as @Visage answer, but the order is different:

public class NameFare {
    private String name;
    private int fare;
    public String getName() {
        return name;
    }
    public int getFare() {
        return fare;
    }
    @Override public void equals(Object o) {
        if (o == this) {
            return true;
        } else if (o != null) {
            if (getName() != null) {
                return getName().equals(o.getName());
            } else {
                return o.getName() == null;
            }
        }
        return false;
    }
}
....
public Collection<NameFare> sortAndMerge(Collection<NameFare> toSort) {
    ArrayList<NameFare> sorted = new ArrayList<NameFare>(toSort.size());
    for (NameFare nf : toSort) {
        int idx = sorted.getIndexOf(nf); 
        if (idx != -1) {
            NameFare old = sorted.get(idx);
            if (nf.getFare() < old.getFare()) {
                sorted.remove(idx);
                sorted.add(nf);
            }
        }
    }
    Collections.sort(sorted, new Comparator<NameFare>() {
        public int compare(NameFare o1, NameFare o2) {
            if (o1 == o2) {
                return 0;
            } else {
                if (o1.getName() != null) {
                    return o1.getName().compareTo(o2.getName()); 
                } else if (o2.getName() != null) {
                    return o2.getName().compareTo(o1.getName()); 
                } else {
                    return 0;
                }
            }
        }
    });
}

Comments

1

I would do it in two stages.

Firstrly sort the list using a custom comparator.

Secondly, traverse the list and, for duplicate entries (which will now be adjacent to each other, provided you worte your comparator correctly), remove the entries with the higher values.

Comments

1

If you want to avoid duplicates, perhaps a class like TreeSet would be a better choice than List.

Comments

0

I would use an ArrayList like this:

ArrayList<Name> listOne = new ArrayList<Name>();
listOne.add(new Name("Nellai", 10);
listOne.add(new Name("Gujarath", 10);
listOne.add(new Name("Delhi", 30);
listOne.add(new Name("Nellai", 5);
listOne.add(new Name("Delhi", 20);

Collection.sort(listOne);

Then create the Name class

    class name implements Comparable
{
private String name;
private int number;

public Name(String name, int number)
{
this.name= name;
this.number= number;
}

public String getName()
{
        return this.name;
}
public int getNumber()
{
        return this.number;
} 
public int compareTo(Object otherName) //  must be defined if we are implementing //Comparable interface
{
 if(otherName instanceif Name)
{
throw new ClassCastException("Not valid Name object"):
}
Name tempName = (Name)otherName;
// eliminate the duplicates when you sort 
if(this.getNumber() >tempName.getNumber())
  {
     return 1;
  }else if (this.getNumber() < tempName.getNumber()){
     return -1;
  }else{
     return 0;
  }
}

}

I didn't compiled the code, it's edited here so you should fix the code. And also to figure out how to eliminate the duplicates and print only the lowest one.

You need to sweat too.

5 Comments

As you pointed out, you did not remove duplicates and implementing the compare method inside the Name class is not the best way to deal with the issue in the general case.
1st I don't believe it's alright to give him the answer and him to just copy/paste. He need to work too.
2nd you need to override abstract method compareTo inside the Name class.
1st. I agree, that's why it's better to give a clue about the algorithm instead of pieces of code. 2nd. The issue is that compareTo method must be coherent with equals. So implementing the Comparable interface the way you do it means that 2 Names are equal if they have the same number... awkward.
You are right, I tried using your idea and it's much elegant, I agree with you. But my point was to give him an idea and he should work on that idea. It's much easy when you have a little code and lots of ideas.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.