0

I am new to java and help some help in implementing Comparator. I have an Arraylist of type QualityData with the following values.

**Sequence Nr**  **Súb Sequence_nr** **flag**
        100             1              True
        100             1              False
        101             1              True
        100             2              False
        100             1              False
        100             3              True

Desired Output Order: orderíng based on Sequence_Nr and Sub_sequence_nr.

  **Sequence Nr**  **Súb Sequence_nr**  **flag**
         100              1               True
         100              1               False
         100              1               False
         100              2               False
         100              3               True
         101              1               True

I have a class with Sequence_number, sub_sequence_number and a boolean flag.

public class QualityData{
private int sequence_number;
private int sub_sequence_nr;
private boolean flag; 
//GETTER, SETTER METHODS
public static Comparator<QualityData> COMPARATOR=new Comparator<QualityData>(){
    public int compare(QualityData data1, QualityData data2){
        return int (data1.getSequence_nr()-data2.getSequence_nr());
    }
};
}

And I sort by calling:

List<QualityData> qData= ie.getQualityData();
Collections.sort(qData,QualityData.COMPARATOR);

Here, I have implemented the comparator based on the sequence_number But i want it to be based on the sequence_number and the sub_sequence_nr. Could someone please help me?

java_learner
  • 182
  • 3
  • 13

2 Answers2

3

I am not posting exactly working solution here, but this will give complete idea to what you need and how to solve it

       public static Comparator<QualityData> COMPARATOR=new Comparator<QualityData>(){
            public int compare(QualityData data1, QualityData data2){
                if((data1.getSequence_nr()-data2.getSequence_nr() == 0)){
                    if(data1.getSubSequence_nr()-data2.getSubSequence_nr() == 0){
                        if(data1.getFlag()){
                           return 1;    
                        }else{
                            return -1;
                        }
                    }else{
                        return data1.getSubSequence_nr()-data2.getSubSequence_nr();
                    }
                }else {
                    return data1.getSequence_nr()-data2.getSequence_nr();
                }
            }
        };
        }
RaceBase
  • 18,428
  • 47
  • 141
  • 202
0

You need to use that Comparator while using Collections.sort(collection, comparator);


Also See

Community
  • 1
  • 1
jmj
  • 237,923
  • 42
  • 401
  • 438
  • 2
    I guess OP is confused about how to use desired field to compare values. He want to consider 3 fields for comparison. – Ajinkya Jul 22 '13 at 06:56