Home > OS >  List sorting, if integers are same that related strings should be in alphabetical order and the inte
List sorting, if integers are same that related strings should be in alphabetical order and the inte

Time:12-24

The Dart list should be sorted alphabetical based on the same integer value inside the element object. If the integer has same values those related strings should be in aplhabetical and ascending order

Here is the list.

List items = [ People( 10 , 'a' ) , People( 5 , 'c' ), People( 15 , 'b' ), People( 15 , 'a' ), People( 5 , 'k' ), People( 10 , 'd' ) People( 7, 'c' )];

Expected result :

List items = [ People( 5 , 'c' ) , People( 5 , 'k' ), People( 7 , 'c' ), People( 10 , 'a' ), People( 10 , 'k' ), People( 15 , 'a' ) People( 15, 'd' )];

CodePudding user response:

@Pskink already mentioned, First you need to alphabetically sort then you go with number

void main() {
  List items = [
    People(10, 'd'),
    People(5, 'c'),
    People(15, 'b'),
    People(15, 'a'),
    People(5, 'k'),
    People(10, 'a'),
    People(7, 'c')
  ];
  items.sort((a, b) => ("${a.title}")
      .toString()
      .compareTo(("${b.title}").toString()));
  
  items.sort((a, b) => (a.number)
      .compareTo((b.number)));

  

  items.forEach((e)=>print("${e.number} ${e.title}"));
}

output:

5 c
5 k
7 c
10 a
10 d
15 a
15 b

CodePudding user response:

No need of the double sorting suggested by Jahidul Islam. You just need to make a compare method which compares the name in case the number is the same. So something like this:

void main() {
  final items = [
    People(10, 'a'),
    People(5, 'c'),
    People(15, 'b'),
    People(15, 'a'),
    People(5, 'k'),
    People(10, 'd'),
    People(7, 'c'),
  ];

  print(items);
  // [People(10,'a'), People(5,'c'), People(15,'b'), People(15,'a'), People(5,'k'), People(10,'d'), People(7,'c')]

  items.sort((p1, p2) {
    final compareAge = p1.age.compareTo(p2.age);

    if (compareAge != 0) {
      return compareAge;
    } else {
      return p1.name.compareTo(p2.name);
    }
  });

  print(items);
  // [People(5,'c'), People(5,'k'), People(7,'c'), People(10,'a'), People(10,'d'), People(15,'a'), People(15,'b')]
}

class People {
  final int age;
  final String name;

  People(this.age, this.name);

  @override
  String toString() => "People($age,'$name')";
}
  • Related