Home > Software design >  How to sort a list twice in Flutter?
How to sort a list twice in Flutter?

Time:12-14

I want to sort the list twice.

Example list (here is an example list with models):

[Model("A", 5), Model("C", 3), Model("B", 7) Model("F", 5), Model("D", 5)]

What I want is to sort alphabetically and then numerically. If I do this, I get the following result:

[Model("C", 3), Model("A", 5), Model("D", 5) Model("F", 5), Model("B", 7)]

Else:

Sort alphabetically:

[Model("A", 5), Model("B", 7), Model("C", 3) Model("D", 5), Model("F", 5)]

Sort numerically:

[Model("C", 3), Model("A", 5), Model("F", 5) Model("D", 5), Model("B", 7)]

My code:

Stream<List<T>> function<T>({
  …
  int Function(T lhs, T rhs) sort,
}) {
  …
  List<T> result = …;
  result.sort(sort);
}

Stream<List<Model>> stream() {
  return function(
    …
    sort: (a, b) => a.alphabet.toLowerCase().compareTo(b.alphabetc.toLowerCase())
  );
}

Feel free to leave a comment if you need more information.

How to sort a list twice? I would appreciate any help. Thank you in advance!

CodePudding user response:

You can call it twice after each other like this:

modelList.sort(
  (a, b) => a.alphabet.compareTo(b.alphabet),
);
modelList.sort(
  (a, b) => a.number.compareTo(b.number),
);

in your case:

Stream<List<T>> function<T>({
  …
  
  int Function(T lhs, T rhs) sort1,
  int Function(T lhs, T rhs) sort2,
}) {
  …
  List<T> result = …;
  result.sort(sort1);
  result.sort(sort2);
}

result :

for (var element in modelList) {
  print("element = ${element.alphabet}"); //C, A, D, F, B
}

CodePudding user response:

there is a first obvious solution, and it's by sorting your list multiple time, which mean more time and space complexity, you can achieve the result with a single sort().

Try the following code, first, implement the Comparable class on you Model class, and implement the compareTo method like this:

class Model implements Comparable {
  final String char;
  final int number;

  Model(this.char, this.number);

  @override
  toString() {
    return "Model('$char', '$number')";
  }
  
  @override
  int compareTo(other) {

    if (other is Model) {
      if (number == other.number) {
        return other.char.compareTo(char);
      } else {
        return other.number.compareTo(number);
      }
    } else {
      return 0;
    }
  }
}

Then, taking this example

List<Model> a = [
    Model("A", 5),
    Model("C", 3),
    Model("B", 7),
    Model("F", 5),
    Model("D", 5),
  ];

Trying to sort it will get you to your desired result:

a.sort((a, b) => b.compareTo(a) );
print(a); // [Model('C', '3'), Model('A', '5'), Model('D', '5'), Model('F', '5'), Model('B', '7')]
  • Related