Scala - Everyday tool components

I. Introduction

The development is mainly based on scala, some common tool components are recorded, and they are continuously updated from time to time...

2. Daily tool components

1. Repeating characters

Used when printing normalized logs, for a specified number of characters.

  def repeatString(char: String, n: Int): String = List.fill(n)(char).mkString

use:

    println(repeatString("=", 100))
====================================================================================================

2. Format numbers

For data reporting and display, the double specification is in the format of percent sign and x decimal point.

import java.text.DecimalFormat
  
  def formatRatio(ratio: Double): String = {
    val decimalFormatter = new DecimalFormat("0.000%")
    val formatted_num = decimalFormatter.format(ratio)
    formatted_num
  }

use:

    val num = 0.034879347834726
    val forMatNum = formatRatio(num)
    println(forMatNum)
3.488%

3.Redis Hmset

When using Jedis to execute redis.hmset, it is found that scala.collection.mutable.HashMap[String, String] and java.util.Map[String, String] are not available, switch java.uitl.HashMap to use normally.

      val map = new util.HashMap[String, String]()
      redis.hmset(saveKey, map)
  def toLog(args: String*): String = {
    args.toArray.mkString("\t")
  }

4. Loop through the dates

To execute the task, you need to process multiple days of data at the same time and get the results. You can first obtain all dt in the code, and then process the final summary separately.

  def traverseDate(): Unit = {
    val dateTimeFormat = DateTimeFormatter.ofPattern("yyyyMMdd")

    val st = "20210101"
    val end = "20210315"
    var now = st
    val allDateTime = new ArrayBuffer[String]()

    while (now.toInt <= end.toInt) {
      allDateTime.append(now)
      now = LocalDate.parse(now, dateTimeFormat).plusDays(1).format(dateTimeFormat)
    }

    allDateTime.foreach(println)
  }

5. Variable length log

When the task output log, it often encounters the situation of variable length. It is more troublesome to use StringBuilder or StringBuffer, and it needs to be appended all the time. It can be easily solved by using scala variable-length parameters, which is very easy to use.

  def toLog(args: String*): String = {
    args.toArray.mkString("\t")
  }
    println(toLog("A", "B", "C", "D"))
    println(toLog("A", "B", "C", "D", "E", "F"))

6. Quick Try Catch

Scala's traditional try catch is very complicated to write. For some simple scenarios such as feature acquisition and transformation, it does not need to be so complicated. Just introduce scala.util.Try to quickly try catch.

  def tryCatch(): Unit = {
    val numStr = "NULL"

    val num = try {
      numStr.toInt
    } catch {
      case e: Exception => {
        e.printStackTrace()
        0L
      }
    }
    println(num)

Quick try-catch:

   val quickNum = Try(numStr.toInt).getOrElse(0)
   println(quickNum)

Guess you like

Origin blog.csdn.net/BIT_666/article/details/124099853