1 | /******************************************************************************* | |
2 | * Copyhacked (H) 2012-2020. | |
3 | * This program and the accompanying materials | |
4 | * are made available under no term at all, use it like | |
5 | * you want, but share and discuss about it | |
6 | * every time possible with every body. | |
7 | * | |
8 | * Contributors: | |
9 | * ron190 at ymail dot com - initial implementation | |
10 | ******************************************************************************/ | |
11 | package com.jsql.view.swing.table; | |
12 | ||
13 | import java.util.Comparator; | |
14 | ||
15 | /** | |
16 | * Comparator for table column values ; column with only int data is sorted like 3 lt 20 lt 100, | |
17 | * column with string will sort like 100 gt 20 gt 3 gt abc. | |
18 | */ | |
19 | public class ComparatorColumn<T> implements Comparator<T> { | |
20 | | |
21 | /** | |
22 | * Custom compare to sort numbers as numbers. | |
23 | * Strings as strings, with numbers ordered before strings. | |
24 | * @param cellLeft | |
25 | * @param cellRight | |
26 | * @return | |
27 | */ | |
28 | @Override | |
29 | public int compare(T cellLeft, T cellRight) { | |
30 | | |
31 | var isFirstNumber = true; | |
32 | var isSecondNumber = true; | |
33 | | |
34 | String valueCellLeft = cellLeft.toString().trim(); | |
35 | String valueCellRight = cellRight.toString().trim(); | |
36 | ||
37 | try { | |
38 | Long.parseLong(valueCellLeft); | |
39 | } catch (NumberFormatException e) { | |
40 | isFirstNumber = false; | |
41 | } | |
42 | | |
43 | try { | |
44 | Long.parseLong(valueCellRight); | |
45 | } catch (NumberFormatException e) { | |
46 | isSecondNumber = false; | |
47 | } | |
48 | | |
49 | int sortOrder; | |
50 |
2
1. compare : negated conditional → NO_COVERAGE 2. compare : negated conditional → NO_COVERAGE |
if (isFirstNumber && isSecondNumber) { |
51 | sortOrder = Long.valueOf(valueCellLeft).compareTo(Long.valueOf(valueCellRight)); // or Sort by Number | |
52 |
1
1. compare : negated conditional → NO_COVERAGE |
} else if (isFirstNumber) { |
53 | sortOrder = -1; // or Sort by Number first | |
54 |
1
1. compare : negated conditional → NO_COVERAGE |
} else if (isSecondNumber) { |
55 | sortOrder = 1; // or Sort by Letter first | |
56 | } else { | |
57 | sortOrder = valueCellLeft.compareToIgnoreCase(valueCellRight); // Sort by Letter | |
58 | } | |
59 | | |
60 |
1
1. compare : replaced int return with 0 for com/jsql/view/swing/table/ComparatorColumn::compare → NO_COVERAGE |
return sortOrder; |
61 | } | |
62 | } | |
Mutations | ||
50 |
1.1 2.2 |
|
52 |
1.1 |
|
54 |
1.1 |
|
60 |
1.1 |