The scene of a

Before a net friend who just graduated to work asked me a question, want to sort a collection

As shown above, you want to sort this collection by the value of the checkLineLocation field. After all, I have been working for more than a year, and I have more experience than him. First of all, I must ask what the sorting rule is, and I cannot use the default dictionary sorting of String.

He said in this diagram from left to right, left wall, left arch, vault, right arch, right wall. Now we know the collation, but the checkLineLocation is a String and has its own default collation, so we need to create a mapping for this field and then write another collation. So the first thing that comes to mind is using enumerations.

Start by defining an enumerated class

Public enum LineLocationEnum {location_waist (" top ",3) {location_waist (" top ",3) { LOCATION_RIGHT_WAIST(" right waist ",4), LOCATION_RIGHT_WALL(" right wall ",5); LineLocationEnum(String location,int sort){ this.location = location; this.sort = sort; } @Getter private final String location; @Getter private final int sort; Public static int getSortByLocation(String location) {return array.stream (LineLocationEnum. Values ()) .filter(orderStatusEnum -> orderStatusEnum.getLocation().equals(location)) .map(LineLocationEnum::getSort) .findFirst() .orElse(0); }}Copy the code

This gives a collation sort to the checkLineLocation association and provides the method getSortByLocation to get the sort value sort based on location. Then write code to test it

public static void main(String[] args) { List<CheckDataReport> list = new ArrayList<CheckDataReport>(){{ add(new CheckDataReport (" vault ")); Add (new CheckDataReport(" right wall ")); Add (new CheckDataReport(" left arch ")); Add (new CheckDataReport(" left wall ")); Add (new CheckDataReport(" right arch ")); }}; / / sort the list. The sort (Comparator.com paringInt (o - > LineLocationEnum. GetSortByLocation (o.g etCheckLineLocation ()))); System.out.println(list); }Copy the code

The sorting problem is solved by making the fields sort according to our rules, then calling the collection’s sort method and using our sorting rules in the anonymous class of the implementation’s Comparator interface.

The advantage of enumerations is that they can symbolize some numbers, which in turn makes the program more readable. For example, we can also create a new HashMap in the program to store the corresponding sort value, and then sort, but the code is too many, and the readability is poor. Using enumerations is a small amount of code, and once the enumerations are defined, they can be reused in similar scenarios next time.

Scenario 2

Some fields in the work may be stored in the database as numbers representing specific Chinese descriptions, such as order status.

10: to be paid, 15: to be paid balance 20: to be shipped, 30: to be received, 40: completed,50: closed, 60 refunded, 70 refunded

If it is a web list, we can return the number to the front end

@schema (description = "Suborder status, 10: to be paid, 20: to be shipped, 30: to be received, 40: completed, 50: closed,60: refunded,70: refunded ") private Integer childOrderStatus;Copy the code

But one scenario is excel export, which has nothing to do with the front end. The back end simply returns the Excel stream to the browser, so we need to return the corresponding description directly. Enumerations can also be used at this point.

@requiredargsconstructor public constructor constructor public enum OrderStatusEnum {WAIT_PAY(10, "to be paid "), //... Public static String getDescByCode(Integer code) {return Array.stream (OrderStatusEnum. Values ()) .filter(orderStatusEnum -> orderStatusEnum.getCode().equals(code)) .map(OrderStatusEnum::getDesc) .findFirst() .orElse(StringUtils.EMPTY); }}Copy the code

Just use getDescByCode in the assembly Excel return entity class to get the order status description. Instead of using enumerations, use the switch structure inside the method when setting the order status

 switch (status) {
            case 10:
                //...
                break;
            case 15:
                //...
                break;
            case 20:
                 //...
Copy the code

This is a lot of code, not as readable as using enumerations, and you’ll need to write this code inside another method next time.

Encapsulated utility class

As you may have noticed, the getDescByCode method above is written inside an enumeration class. In normal projects, enumerations are at least a dozen or twenty, and it violates the DRY (Dont Repeat Yourself) principle if each class writes such a single piece of code repeatedly. So we can wrap a utility class and define the enumeration interface first

    public interface GenericEnum {
        Integer getCode();
        String getDesc();
    }
Copy the code

Then our enumerated classes implement this interface and define generic methods in conjunction with our previous generics article

Public static <T extends GenericEnum> T getEnumByCode(Integer code, Class<T> enumClass) { return Arrays.stream(enumClass.getEnumConstants()) .filter(t -> t.getCode().equals(code)) .findFirst().orElse(null); } /*** * public static <T extends GenericEnum> String getEnumDescByCode(Integer code, Class<T> enumClass) { return Arrays.stream(enumClass.getEnumConstants()) .filter(t -> t.getCode().equals(code)) .map(T::getDesc).findFirst() .orElse(null); }}Copy the code

conclusion

The right scenario for enumerations is to define a finite set of collections, such as color, status, coupon type, shipping status, and so on. This article has listed two scenarios in which bloggers use enumerations, and more will be updated in the future.

Please like and follow this article if it’s been helpful to you. Your support is my motivation to continue to create!