user7700572
user7700572

Reputation:

How to sort substring in collection?

How I can sort this by year then by bc?

List<String> spzn = new ArrayList<String>;

for(final CcaesItem item : items) { //Items is List<CcaesItem>
    Long bc = item.getBcItem();
    Long year = item.getYear();
    String type = item.getType();
    spzn.add(type + " " + bc + "/" + year);  
}
Collection.sort(spzn);

I had idea to use substring, but collection.sort didn't work with substring.

Upvotes: 1

Views: 1004

Answers (4)

Dhara Jani
Dhara Jani

Reputation: 461

It is example of student having roll number, name and address. The first is without sort data and second one is with roll number sorting data.

ArrayList<Student> ar = new ArrayList<Student>();
ar.add(new Student(111, "bbbb", "london"));
ar.add(new Student(131, "aaaa", "nyc"));
ar.add(new Student(121, "cccc", "jaipur"));

System.out.println("Unsorted");
for (int i=0; i<ar.size(); i++)
    System.out.println(ar.get(i));

Collections.sort(ar, new Sortbyroll());

System.out.println("\nSorted by rollno");
for (int i=0; i<ar.size(); i++)
    System.out.println(ar.get(i));

class Sortbyroll implements Comparator<Student>
{
    // Used for sorting in ascending order of
    // roll number
    public int compare(Student a, Student b)
    {
        return a.rollno - b.rollno;
    }
}

Upvotes: 0

Vlad Bochenin
Vlad Bochenin

Reputation: 3072

Collections.sort can gets instance of Comparator as second argument. In the Comparator you can put any code to compare two list's items.

For example will sort spzn by year and getBcItem:

    Collections.sort(spzn, new Comparator() {
        @Override
        public int compare(CcaesItem  o1, CcaesItem  o2) {
            if (o1.getYear() > o2.getYear()) {
                return 1;
            } else if (o1.getYear() < o2.getYear()) {
                return -1;
            } else {
                if (o1.getBcItem() > o2.getBcItem()) {
                    return 1;
                } else if (o1.getBcItem() < o2.getBcItem()) {
                    return -1;
                }
            }

            return 0;
        }
    });

Also don't forget about null checks in Comparator because list can contains null values

Upvotes: 2

Mạnh Quyết Nguyễn
Mạnh Quyết Nguyễn

Reputation: 18235

You can sort your list first:

List<String> result = 
     items.stream()
     .sorted(Comparator.comparingLong(CcaesItem:: getYear).thenComparingLong(getBcItem))
     .map(c -> c.getType() + " " + c.getBcItem() + "/" + c.getYear())
     .collect(toList());

Upvotes: 0

Karol Dowbecki
Karol Dowbecki

Reputation: 44932

Sort the items collection before creating your custom Strings.

List<String> spzn = items.stream()
  .sorted(Comparator.comparing(CcaesItem::getYear).thenComparing(CcaesItem::getBcItem))
  .map(vec -> vec.getType() + " " + vec.getBcItem() + "/" + vec.getYear())
  .collect(Collectors.toList());

Upvotes: 1

Related Questions