Hutool tools are not confused

 

Foreword

This is the third day of my participation in the revision challenge in November. See the activity details: the last revision challenge in 2021. Are you still encapsulating tool classes and tool methods in the project? Let Hutool help you. It is a friendly alternative to the util package in the project, covering all aspects of the bottom layer of Java development. It is not only a sharp tool to solve small problems in large projects, but also an efficiency responsibility in small projects. It can enable you to focus on business, greatly improve development efficiency, and avoid small problems and bugs in self encapsulation to the greatest extent. Therefore, it is very necessary to learn how to use the tools and methods required in the project development process efficiently and accurately. Today, I will share some practical tool methods with you in combination with the use scenarios. I hope you will forgive me for what I didn't explain clearly and what I didn't involve. For details, please refer to Hutool's official website (hutool.cn).

introduce

Hutool , contains JDK methods such as file, stream, encryption and decryption, transcoding, regularization, thread and XML, which are placed in different module components. When you need to operate on , Excel , you can introduce , hutool poi , module separately. Of course, you can't distinguish the functions between modules, which is easy. You can also introduce all modules by introducing , hutool all ,.

Maven

<dependency>
    <groupId>cn.hutool</groupId>
    <artifactId>hutool-all</artifactId>
    <version>5.7.16</version>
</dependency>

Gradle

implementation 'cn.hutool:hutool-all:5.7.16'

use

Let's share some frequently used tools and methods, and welcome comments (^ ▽ ^)

Console object information printing class

Those who are familiar with , JS , must be familiar with these two methods, even "old friends". In fact, the , Console , object in , Hutool , draws lessons from the syntax sugar in , JS ,. Although it is printing, and {system out. println() / System. err. Println () is different. The most important thing is that it supports Slf4j's string template syntax and automatically converts objects (including arrays) to string form.

Code example:

Console.log("this is array: {}", new String[]{"Java", "JavaScript", "Python"});

Console.error("I'm a red error message.");

As a template placeholder, {} here can pass in the variable values to the right of the comma in turn, so as to print out in the form of string.

Convert convert classes between different types

This class encapsulates conversions for common types of Java. It is used to simplify type conversion. At the same time, it has a good encapsulation for exception capture of conversion failure, which can help you reduce the bloated business code and improve the elegance of the code. This tool class is still very common and practical. It must be Amway ̀ ◡• ́ ๑)૭

Code example:

// Convert to string
int number = 10;
Console.log("After converting to string:{}", Convert.toStr(number));

int[] arr = {1, 2, 3, 4, 5};
Console.log(Convert.toStr(arr, "Convert to string fail! This is default value."));

// Converts to an array of the specified type
String[] letters = {"12", "122", "1223", "1211"};
Console.log(Convert.toShortArray(letters));
Console.log(Convert.toStrArray(arr));

float[] floatArr = {1.2F, 1.3F, 2.0F, 3.14f};
Integer[] integerArr = Convert.toIntArray(floatArr);
Console.log(integerArr); // [1, 1, 2, 3]

// Convert to date object
String strDate1 = "2021-10-11 12:03:29";
// toDate
Console.log("The string of data convert to Date: {}", Convert.toDate(strDate1)); // 2021-10-11 12:03:29
// toLocalDateTime
Console.log("The string of data convert to LocalDateTime: {}", Convert.toLocalDateTime(strDate1)); // 2021-10-11T12:03:29

// Convert to collection
String[] langs = {"Java", "JavaScript", "Python", "C++", "GoLang", "TypeScript", "Kotlin"};

// Via convert The convert (class < T >, object) method can convert any type to the specified type
ArrayList arrayList = Convert.convert(ArrayList.class, langs);
// You can also turn the set like this
List<String> langList = Convert.toList(String.class, langs);
Console.log("String array is converted to ArrayList: {}", arrayList);
Console.log("String array is converted to List: {}", langList);
// Convert to a collection of the specified type
Object[] objArr = {"a", "you", "good", "", 1};
// TypeReference objects can type convert nested generics
List<String> strList = Convert.convert(new TypeReference<List<String>>() {
}, objArr);
Console.log("use TypeReference Object can type convert nested generics:{}", strList);

Convert string to hexadecimal (Hex) and Unicode string

// Convert string to hexadecimal (Hex)
String desc = "Hello, my name is HUALEI !";
// Because the string involves encoding problems, the encoding object must be passed in
String hexStr = Convert.toHex(desc, CharsetUtil.CHARSET_UTF_8);
Console.log("Convert string to Hex character string:{}", hexStr); // e5a4a7e5aeb6e5a5bdefbc8ce68891e79a84e5908de5ad97e58fab204855414c454920efbc81

// Hex string conversion back
String originStr = Convert.hexToStr(hexStr, CharsetUtil.CHARSET_UTF_8);
Console.log("take Hex Convert string back to original string:{}", originStr);

/*
    If all kinds of character codes are described as local dialects, Unicode is a language developed by countries all over the world.

    String is converted to Unicode (unified code / universal code / single code), which is to solve the disadvantages of traditional character coding schemes (complex and non-uniform, resulting in garbled code caused by inconsistent coding formats)

        Unicode A unified and unique binary encoding is set for each character in each language
        To meet the needs of cross language and cross platform text conversion and processing
*/
// Convert string to Unicode
String unicodeStr = Convert.strToUnicode(desc);
Console.log("Convert string to Unicode String:{}", unicodeStr); // \u5927\u5bb6\u597d\uff0c\u6211\u7684\u540d\u5b57\u53eb HUALEI \uff01

Character encoding mode conversion (encoding and decoding)

String a = "I'm not garbled";
// Encoding and decoding to ISO using UTF8 characters_ 8859_ 1 encoding string
String mess = Convert.convertCharset(a, CharsetUtil.UTF_8, CharsetUtil.ISO_8859_1);
Console.log("ISO_8859_1 Chinese garbled code of coding method:{}", mess); // After conversion, the MES is garbled = > æä, and æä ¹ ±ç 

// Use ISO_8859_1 character encoding is decoded into the string of the original UTF8 encoding mode, and the random code is converted into the correct encoding mode:
String raw = Convert.convertCharset(mess, CharsetUtil.ISO_8859_1, "UTF-8");
Console.log("After converting the garbled code to the correct code:{}", raw); // I'm not garbled

Chinese large / small numbers and amount related conversion

// Amount in Chinese (up to two decimal places)
double money = 18.88D;
String chineseWord = Convert.digitToChinese(money);
Console.log("Amount transferred to Chinese:{}", chineseWord); // Eighteen yuan and eighty-eight cents

// Amount in English (up to two decimal places)
String englishWord = Convert.numberToWord(money);
Console.log("Amount transferred to English:{}", englishWord); // EIGHTEEN AND CENTS EIGHTY EIGHT ONLY

double amount = 102389942.32D;
// Number to Chinese capital (e.g. one thousand, up to two decimal places) isusetraditional = > true
String traditionalChinese = Convert.numberToChinese(amount, true);
// Number to Chinese lowercase (example: 1000) isusetraditional = > false
String nonTraditionalChinese = Convert.numberToChinese(amount, false);
Console.log("Number to Chinese capital, traditional:{};Unconventional:{}", traditionalChinese, nonTraditionalChinese); // Tradition: one hundred and two million three hundred and eighty-nine thousand nine hundred and forty-two point thirty-two; Unconventional: 102.389 million, 942.32

// Chinese capital one thousand three hundred into pure numbers
Console.log("Chinese capital thirteen hundred into numbers:{}", Convert.chineseToNumber("one thousand and three hundred")); // 1300

// Digital simplification 1000 = > 1K; 10000 = > 1W (up to two decimal places)
String simple = Convert.numberToSimple(amount);
Console.log("{} Simplified as:{}", amount, simple); // 10238.99w

The converttime (target value, target value time unit, converted time unit) method is mainly used to convert the time unit, such as a large millisecond. I want to obtain how many days this millisecond is converted into:

// Msec 
long ms = 100000000L;
long msToDays = Convert.convertTime(ms, TimeUnit.MILLISECONDS, TimeUnit.DAYS);
Console.log("{} Milliseconds is approximately equal to {} day", ms, msToDays); // 100000000 milliseconds is approximately equal to 1 day

Conversion between original type and wrapper type

// Integer wrapper class
Class<Integer> wrapClass = Integer.class;

// Integer wrapper class = > int
Class<?> unWraped = Convert.unWrap(wrapClass); // int
Console.log("Integer Packaging depackaging:{}", unWraped);

// Primitive class
Class<?> primitiveClass = long.class;

// Convert original type to wrapper class
Class<?> wraped = Convert.wrap(primitiveClass); // class java.lang.Long
Console.log("long Original packaging:{}", wraped);

DateUtil DateTime tool class

For Java util. Is the date object still in fear of being dominated by {Thu Nov dd HH:mm:ss CST yyyy}? The mixing of abbreviations of digital English words makes people look very uncomfortable. If you want to convert it into a {yyyy MM DD / yyyy MM DD HH: mm: SS} time format string, do you have to} new} a} SimpleDateFormat first and initialize the formatter through the} pattern} parameter. Those who are not proficient in time format may have to Baidu, which is very troublesome.

For convenience, Hutool tool uses a DateTime class to replace it. It inherits from Date, rewrites the toString() method, and directly puts back the string in the form of {yyyy MM DD HH: mm: SS} to facilitate the call during output (such as logging), and provides many convenient methods to operate on Date objects.

Code example:

// Timer to calculate the execution time of the code fragment wrapped by it
final TimeInterval timeInterval = DateUtil.timer();

// Calculate the current age according to birthday
String dateStr = "2000 May 26";
Date birthday = Convert.toDate(dateStr);
// You can specify dateStr date time format through DatePattern for parsing. If there is no second parameter, it will automatically find an appropriate format (supporting multiple formats) for parsing
// DateTime dateTime = new DateTime(dateStr, DatePattern.CHINESE_DATE_PATTERN);
int age = DateUtil.ageOfNow(birthday); // Or dateutil ageOfNow(dateTime);
Console.log("{} Born young man, now {} Years old!", dateStr, age);

// Get the current time, format: yyyy MM DD HH: mm: SS = > datetime type
Date currentDate = DateUtil.date(); // 2021-11-02 08:57:54
// Equivalent to DateTime currentDateTime = new DateTime();
// Different from new date() = > Tue Nov 02 08:57:54 CST 2021
Console.log("DateUtil.date() Get current time( yyyy-MM-dd HH:mm:ss): ", currentDate);

// Converts a special date string to a DateTime object
String strDate2 = "2021 12:03:29 on November 2";
// Converts a string Date to a Date object according to the format template
Console.log("Use DateUtil.parse() method convert to Date: {}", DateUtil.parse(strDate2, "yyyy year MM month dd day HH Time mm branch ss second")); // 2021-11-02 12:03:29
// Equivalent to new DateTime(strDate2);

// Method 1: convert the current millisecond to DateTime, format: yyyy MM DD HH: mm: SS
Date msToDateTime1 = DateUtil.date(Calendar.getInstance()); // 2021-11-02 08:57:54
Console.log("Current milliseconds converted to DateTime Time, mode 1:", msToDateTime1);

// Method 2: convert the current milliseconds into DateTime time, format: yyyy MM DD HH: mm: SS
Date msToDateTime2 = DateUtil.date(System.currentTimeMillis()); // 2021-11-02 08:57:54
Console.log("Current milliseconds converted to DateTime Time, mode 2:", msToDateTime2);

// Current date string, format: yyyy MM DD
String today= DateUtil.today(); // 2021-11-02
Console.log("Current date string, format: yyyy-MM-dd: {}", today);

// Format the Date object as a Date string, format: yyyy MM DD
String formatDateStr = DateUtil.format(new Date(), "yyyy-MM-dd");
Console.log("Use DateUtil.format() method convert to Date: {}", formatDateStr);

// Get the Time string of DateTime, format: HH:mm:ss
String formatTimeStr = DateUtil.formatTime(new DateTime());
Console.log("Use DateUtil.formatTime() method only covert Date to HH:mm:ss: {}", formatTimeStr);

// zodiac sign
String zodiac = DateUtil.getZodiac(DateUtil.month(birthday), ((int) DateUtil.betweenDay(DateUtil.beginOfMonth(birthday), birthday, false)));
// chinese zodiac
String chineseZodiac = DateUtil.getChineseZodiac(DateUtil.year(birthday));
Console.log("{} For birthday people, the constellation is:{},genus {} of", birthday, zodiac, chineseZodiac);

// Judge whether this year is a flat leap year
boolean isLeapYear = DateUtil.isLeapYear(DateUtil.year(new Date()));
Console.log("{}Is leap year?{}", DateUtil.year(new Date()), isLeapYear);

// Get a time spent after beautification, that is, add Chinese units
String spendTimePretty = timeInterval.intervalPretty();
// The running time is converted to seconds
long sec = timeInterval.intervalSecond();

// Returns the elapsed time and resets the start time
long spendTimeAndRestart = timeInterval.intervalRestart();

Console.log("Test run time (no unit, no beautification):", spendTimeAndRestart);
Console.log("Test run time (with unit):", spendTimePretty);
Console.log("Test run time, converted to seconds:{}", sec);

Get the start / end time of the specified day / week / month / quarter / year, and return {DateTime in the format of yyyy MM DD HH: mm: SS

DateTime beginOfDayTime = DateUtil.beginOfDay(new Date());
Console.log("Today's start time:{}", beginOfDayTime); // 2021-11-03 00:00:00

DateTime beginOfYearTime = DateUtil.beginOfYear(new Date());
Console.log("Start time of this year:{}", beginOfYearTime); // 2021-01-01 00:00:00

DateTime endOfYearTime = DateUtil.endOfYear(new Date());
Console.log("End time of this year:{}", endOfYearTime); // 2021-12-31 23:59:59

Date time offset: increases or decreases minutes, hours, days, etc. for a date

// Increase the current time by half an hour
DateTime halfHourLater = DateUtil.offset(currentDate, DateField.MINUTE, 30);
// Equivalent to: dateutil offsetHour(currentDate, 30);
Console.log("current time is {},Half an hour later:{}", currentDate, halfHourLater);
// Now in five days
DateTime fiveDaysFromNow = DateUtil.offsetDay(currentDate, 5);

Console.log("current time is {},Five days later:{}", currentDate, fiveDaysFromNow);
// For the current time, a more simplified offset method is provided
Console.log("Yesterday's today is:{}", DateUtil.yesterday());
Console.log("Today is tomorrow:{}", DateUtil.tomorrow());
Console.log("Last Sunday's is now:{}", DateUtil.lastWeek());
Console.log("Next week's is now:{}", DateUtil.nextWeek());
Console.log("Last month's is now:{}", DateUtil.lastMonth());
Console.log("Next month's is now:{}", DateUtil.nextMonth());

Calculate the interval between two times

// current time 
DateTime currentDateTime = new DateTime();

String dateTimeStrStart = "1949/10/01";
Date startTime = Convert.toDate(dateTimeStrStart);
long betweenDays = DateUtil.between(startTime, new DateTime(), DateUnit.DAY);
Console.log("It has been a long time since the founding of new China {} day", betweenDays);

// Off duty time (17:00:00 on the same day)
Date getOffTime = DateUtil.offsetHour(DateUtil.beginOfDay(currentDateTime), 17);
Console.log("Off duty hours are:{}", getOffTime);
long distance = DateUtil.between(getOffTime, currentDateTime, DateUnit.SECOND, true);

// The interval is set to seconds
Console.log("There's still time to get off work {} second", distance);
// Format interval
Console.log("There's still time to get off work {} Accurate to seconds", DateUtil.formatBetween(getOffTime, currentDateTime, BetweenFormatter.Level.SECOND));

ObjectUtil object information printing class

For the common tool class methods of "Object", it does not distinguish between "String" or "Object", Array "or" Collection ".

Code example:

Determine null / blank string

final String blankStr = "   ";
final String nullStr = null;
final String dateStr = null;

// isEmpty/isNull returns true only if it is null
System.out.println(ObjectUtil.isEmpty(blankStr)); // false
System.out.println(ObjectUtil.isEmpty(nullStr)); // true
System.out.println(ObjectUtil.isNull(nullStr)); // true
System.out.println(ObjectUtil.isNull(blankStr)); // false

// null / space strings are blank
System.out.println(ObjectUtil.defaultIfBlank(blankStr, "The target string is empty. I am the default")); // Go to defaultValue
System.out.println(ObjectUtil.defaultIfBlank(nullStr, "The target string is empty. I am the default")); // Go to defaultValue

// Judge here that if dateStr is null, call ` instant Now() `, if it is not null, execute ` dateutil parse`
System.out.println(ObjectUtil.defaultIfNull(dateStr, () -> DateUtil.parse(dateStr, DatePattern.NORM_DATETIME_PATTERN).toInstant(), Instant.now()));

System.out.println(ObjectUtil.defaultIfNull(nullStr, "Target string is null ,I am the default")); // Go to defaultValue
System.out.println(ObjectUtil.defaultIfNull(blankStr, "Target string is null ,I am the default")); // blankStr

Note: objectutil Isnull () method cannot judge whether the fields in the object are empty. If you need to check whether the fields in the Bean object are all empty, you need to use {beanutil Isempty() method.

Judge whether two objects are equal, which is equivalent to {objects Equals() method

ObjectUtil.equals(nullStr, dateStr); // true
ObjectUtil.equals("HUALIE", "HUALEI"); // true

// Equivalent to
Objects.equals(nullStr, dateStr); // true

Calculate object length

int[] array = new int[]{1,2,3,4,5};
// Calculate array length
int length = ObjectUtil.length(array); // 5

Map<String, String> map = new HashMap<>();
map.put("a", "a1");
map.put("b", "b1");
map.put("c", "c1");

// Calculate Map size
length = ObjectUtil.length(map); // 3

If it is a string, call its length() method, the collection class calls its size() method, the array calls its length attribute, and other traversable objects traverse the calculated length.

Never create a collection like this! It's very easy to leak memoryhttps://shimo.im/docs/QR8qXxKHQPcHGCTw/

StrUtil string processing tool

 

↑ is similar to this class, but compared with StringUtils, this class is shorter and more lazy [dog head]. The commonly used methods in this class are ↑ isBlank(), isNotBlank(), isEmpty(), and isNotEmpty(), which are mainly used to judge the null of strings, so I won't repeat it here.

Code example:

// Remove prefix
String[] tableNames = {"tb_user", "t_mall", "province", "t_capital", "tb_task"};
for (int i = 0; i < tableNames.length; i++) {
    if (StrUtil.containsAnyIgnoreCase(tableNames[i], "tb_", "t_")) {
        // Remove prefix and ignore case
        tableNames[i] = StrUtil.removePrefixIgnoreCase(tableNames[i], "tb_");
        // Remove prefix and ignore case
        tableNames[i] = StrUtil.removePrefixIgnoreCase(tableNames[i], "t_");
    }
}
Console.log("After removing the table name prefix:{}", (Object) tableNames); // [user, mall, province, capital, task]

// Remove suffix
String fileName = StrUtil.removeSuffix("HUALEI.png", ".png");
Console.log("Remove file.After extension:{}", fileName); // HUALEI

// Character creation constants, including dots, empty strings, line breaks, and some escape characters in HTML
System.out.println(StrUtil.AT.concat("HUALEI").concat(StrUtil.DOT).concat(StrUtil.LF)); // @HUALEI.

// Use string template instead of string splicing
String template = "{}love{},I love you, honey snow ice city{}";
String str = StrUtil.format(template, "you", "I", "Sweet honey"); // You love me, I love you, honey Snow Ice City, sweet honey

Colutil | colstreamutil collection processing tool class

These two classes mainly encapsulate the operation methods of array, list and other collection classes. Collection accounts for a large part in the development and must be mastered to improve our development efficiency.

Code example:

Simulate database sorting and paging, and return a PageResult

List<Fruit> fruits = fruitMapper.selectList(Wrappers.emptyWrapper());

// Total records
long totalCount = fruits.size();
// Current page
int currentPage = 1;
// Records per page
int pageSize = 10;

// The current page index, starting from 0, represents the first page
int pageNo = currentPage - 1;

// Default paging list
List<Fruit> defaultPageList = CollUtil.page(pageNo, pageSize, fruits);

// Sort the paging list by record update time
List<Fruit> orderPageList = CollUtil.sortPageAll(pageNo, pageSize, Comparator.comparing(Fruit::getUpdateTime), fruits);

// Reassemble the PageResult paging result object with paging parameters and record list
PageResult pageResult = new PageResult(orderPageList, totalCount, pageSize, currentPage));

System.out.println("Current pages:" + pageResult.getCurrPage());
System.out.println("Records per page:" + pageResult.getPageSize());
System.out.println("Total records:" + pageResult.getTotalCount());
System.out.println("Total pages:" + pageResult.getTotalPage());
// Current page record list
pageResult.getList().forEach(System.out::println);

Get header alias mapping

// List of field names
List<String> headerNameList = new ArrayList<>();

// Use the reflection tool to get all header names
for (Field field : ReflectUtil.getFields(ProvinceExcelVO.class)) {
    if (!StrUtil.equals(field.getName(), "serialVersionUID")) {
        headerNameList.add(field.getName());
    }
}
// Header alias list
List<String> aliasList = CollUtil.newArrayList("Province name", "abbreviation", "Area( km²)", "Population (10000)", "Famous scenic spot", "Postal Code", "provincial capital", "Nickname", "Climate type", "license plate number");

// One to one correspondence to form header alias mapping
Map<String, String> headerAliasMap = CollUtil.zip(fieldNameList, aliasList);

Create a Map between the province name and the province object

// All province information in the province table
List<Province> provinces = provinceMapper.selectList(Wrappers.emptyWrapper());

// Use the CollStreamUtil collection flow tool to solve the problem in one line of code
Map<String, Province> provinceMap = CollStreamUtil.toIdentityMap(provinces, Province::getProvince);

// Equivalent to
Map<String, List<Province>> provinceMap =
        provinces.stream()
                .collect(Collectors.toMap(Province::getProvince, Arrays::asList));

// Also equivalent to, combined with Convert method 2:
Map<String, List<Province>> provinceMap =
        provinces.stream()
                .collect(Collectors.toMap(Province::getProvince, p -> Convert.toList(Province.class, p)));

// Obtain the provincial information of Jiangxi Province
Console.log("The provincial information of Jiangxi Province is:{}", provinceMap.get("Jiangxi Province"));

Group all provinces by primary key # pid #

Map<Integer, List<Province>> groupByKey = CollStreamUtil.groupByKey(CollUtil.unionAll(provinces, provinces), Province::getPid);

// Equivalent to
Map<Integer, List<Province>> groupByKey = CollUtil.unionAll(provinces, provinces).stream()
                .collect(Collectors.groupingBy(Province::getPid, Collectors.toList()));

Extract the province name in the province information list

        
List<String> provinceNameList = CollStreamUtil.toList(provinces, Province::getProvince);

// Equivalent to
List<String> provinceNameList = provinces.stream()
        .map(Province::getProvince)
        .collect(Collectors.toList());

The two - map s merge according to the - key. The final result is expected to be: (key: pid, value: Province) + "-" + abbr (province abbreviation))

// (key: pid, value: province)             
Map<Integer, String> pidToProvince = CollStreamUtil.toMap(provinces, Province::getPid, Province::getProvince);

// Equivalent to
Map<Integer, String> pidToProvince =
        provinces.stream()
                .collect(Collectors.toMap(Province::getPid, Province::getProvince));
                
// (key: pid, value: abbr)      
Map<Integer, String> pidToAbbr = CollStreamUtil.toMap(provinces, Province::getPid, Province::getAbbr);

// Equivalent to
Map<Integer, String> pidToProvince =
        provinces.stream()
                .collect(Collectors.toMap(Province::getPid, Province::getAbbr));

// Merge maps according to the key. If the keys are the same, follow the merge rule
Map<Integer, String> mergeResult = CollStreamUtil.merge(pidToProvince, pidToAbbr, (province, abbr) -> province + "-" + abbr);

RandomUtil random tool

RandomUtil tool class is mainly used to encapsulate Random objects and generate Random numbers / lists. Although it is a pseudo-Random number, it is still sufficient for most use scenarios.

Code example:

// Generates a random integer within the specified range
for (int i = 0; i < 10; i++) {
    System.out.println(RandomUtil.randomInt(0, 100));
}

List<String> randomList = new ArrayList<>();
// Generate a random string (only numbers and characters)
for (int i = 0; i < 10; i++) {
    randomList.add(RandomUtil.randomString(5));
}

// Take 5 numbers randomly from the specified list
List<Integer> eleList = RandomUtil.randomEleList(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10), 5);

// Randomly extract 5 strings from the string list without repetition (the number of extracted strings cannot exceed the size of the list)
Set<String> eleSet = RandomUtil.randomEleSet(randomList, 5);

// The weight random generator passes in the weighted object, and then obtains the object randomly according to the weight
WeightRandom weightRandom = RandomUtil.weightRandom(new WeightRandom.WeightObj[]{new WeightRandom.WeightObj("HUA", 60), new WeightRandom.WeightObj("L", 10), new WeightRandom.WeightObj("EI", 30)});

// Take 10 times at random, and the "HUA" string appears the most
for (int i = 0; i < 10; i++) {
    System.out.println(weightRandom.next());
}

ExcelUtil Excel operation tool class

This class is the secondary encapsulation of the # poi # Library of # Apache # and facilitates the operation of # MS Office # documents. When using this class, users need to import # poi OOXML # dependencies. This package will be automatically associated with the # poi # package, which can well support the # Office2007 + document format.

be careful

Before using, you need to import dependencies:

<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>${poi.version}</version>
</dependency>

If the tool method is not introduced, an error will be reported:

You need to add dependency of 'poi-ooxml' to your project, and version >= 4.1.2

Code example:

// Write to a data source in Excel
List<Province> provinces = provinceMapper.selectList(Wrappers.emptyWrapper());

// Write out file path
String inputPath = "D:/desktop/Export province information.xlsx";
// Create a Writer write object through the tool class
ExcelWriter excelWriter = ExcelUtil.getWriter(inputPath, "Province information table");

// Custom header name (method 1)
excelWriter.addHeaderAlias("pid", "province ID");
excelWriter.addHeaderAlias("province", "province");
excelWriter.addHeaderAlias("abbr", "abbreviation");
excelWriter.addHeaderAlias("area", "Area( km²)");
excelWriter.addHeaderAlias("population", "Population (10000)");
excelWriter.addHeaderAlias("attraction", "Famous scenic spot");
excelWriter.addHeaderAlias("capital", "provincial capital");

// Custom header name (method 2)
Map<String, String> headerAlias = new LinkedHashMap<>(7);

for (Field field : ReflectUtil.getFields(Province.class)) {
    String name = field.getName();
    String alias;
    switch (name) {
        case "pid":
            alias = "province ID";
            break;
        case "province":
            alias = "province";
            break;
        case "abbr":
            alias = "abbreviation";
            break;
        case "area":
            alias = "Area( km²)";
            break;
        case "population":
            alias = "Population (10000)";
            break;
        case "attraction":
            alias = "Famous scenic spot";
            break;
        case "capital":
            alias = "provincial capital";
            break;
        default:
            alias = null;
    }
    if (ObjectUtil.isNotEmpty(alias)) {
        headerAlias.put(field.getName(), alias);
    }
}

// If you use an unordered HashMap, the input parameter header is also unordered. You need to use LinkedHashMap to ensure order
excelWriter.setHeaderAlias(headerAlias);

// Write out the data source into Excel, use the default style, and force the output of the title
excelWriter.write(provinces, true);

// Close the writer to free up memory
excelWriter.close();

ending

Writing is not easy. You are welcome to praise and comment. Your attention and praise are my unremitting driving force. Thank you for seeing here! Peace & Love.

How to solve problems encountered in java learninghttps://shimo.im/docs/PrtyKWjqkqppjQPg/

Keywords: Java Programming Back-end Programmer

Added by Jimmy79 on Mon, 20 Dec 2021 09:38:50 +0200