JAVA平常操做

bean validation 經常使用的註解 (http://www.javashuo.com/article/p-cooiotbt-eo.htmlhtml

Bean Validation 中內置的 constraint     
@Null   被註釋的元素必須爲 null     
@NotNull    被註釋的元素必須不爲 null     
@AssertTrue     被註釋的元素必須爲 true     
@AssertFalse    被註釋的元素必須爲 false     
@Min(value)     被註釋的元素必須是一個數字,其值必須大於等於指定的最小值     
@Max(value)     被註釋的元素必須是一個數字,其值必須小於等於指定的最大值     
@DecimalMin(value)  被註釋的元素必須是一個數字,其值必須大於等於指定的最小值     
@DecimalMax(value)  被註釋的元素必須是一個數字,其值必須小於等於指定的最大值     
@Size(max=, min=)   被註釋的元素的大小必須在指定的範圍內     
@Digits (integer, fraction)     被註釋的元素必須是一個數字,其值必須在可接受的範圍內     
@Past   被註釋的元素必須是一個過去的日期     
@Future     被註釋的元素必須是一個未來的日期     
@Pattern(regex=,flag=)  被註釋的元素必須符合指定的正則表達式     
Hibernate Validator 附加的 constraint     
@NotBlank(message =)   驗證字符串非null,且長度必須大於0     
@Email  被註釋的元素必須是電子郵箱地址     
@Length(min=,max=)  被註釋的字符串的大小必須在指定的範圍內     
@NotEmpty   被註釋的字符串的必須非空     
@Range(min=,max=,message=)  被註釋的元素必須在合適的範圍內

 

 

bigDecimal轉字符串的三種表示方式:

本文介紹BigDecimal的3個toString方法的區別。java

BigDecimal類有3個toString方法,分別是toEngineeringString、toPlainString和toString,git

從BigDecimal的註釋中能夠看到這3個方法的區別:正則表達式

toEngineeringString:有必要時使用工程計數法。工程記數法是一種工程計算中常用的記錄數字的方法,與科學技術法相似,但要求10的冪必須是3的倍數數組

toPlainString:不使用任何指數app

toString:有必要時使用科學計數法tcp

 不使用指數 科學記數法 工程記數法
2700 2.7 × 10³ 2.7 × 10³
27000 2.7 × 10⁴ 27 × 10³
270000 2.7 × 10⁵ 270 × 10³
2700000 2.7 × 10⁶ 2.7 × 10⁶
import java.math.BigDecimal;

public class BigDecimalDemo {
    public static void main(String[] args) {
        BigDecimal bg = new BigDecimal("1E11");
        System.out.println(bg.toEngineeringString());
        System.out.println(bg.toPlainString());
        System.out.println(bg.toString());
    }
}
 
//輸出
100E+9
100000000000
1E+11

計算兩個LocalDateTime類型之間的相差天數使用方法爲:

最開始使用Period.between()方法計算,只能計算相同月份的相差天數:工具

//只能計算相同月之間相隔的天數
int daysNum = Period.between(O.getStartTime().toLocalDate(), O.getEndTime().toLocalDate()).getDays();

優化後使用toEpochDay()方法爲:oop

int daysNum=(int)(o.getEndTime().toLocalDate().toEpochDay() - o.getStartTime().toLocalDate().toEpochDay());

日期轉換:優化

//java.util.Date --> java.time.LocalDateTime
public void UDateToLocalDateTime() {
    java.util.Date date = new java.util.Date();
    Instant instant = date.toInstant();
    ZoneId zone = ZoneId.systemDefault();
    LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, zone);
}

// 02. java.util.Date --> java.time.LocalDate
public void UDateToLocalDate() {
    java.util.Date date = new java.util.Date();
    Instant instant = date.toInstant();
    ZoneId zone = ZoneId.systemDefault();
    LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, zone);
    LocalDate localDate = localDateTime.toLocalDate();
}

// 03. java.util.Date --> java.time.LocalTime
public void UDateToLocalTime() {
    java.util.Date date = new java.util.Date();
    Instant instant = date.toInstant();
    ZoneId zone = ZoneId.systemDefault();
    LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, zone);
    LocalTime localTime = localDateTime.toLocalTime();
}


// 04. java.time.LocalDateTime --> java.util.Date
public void LocalDateTimeToUdate() {
    LocalDateTime localDateTime = LocalDateTime.now();
    ZoneId zone = ZoneId.systemDefault();
    Instant instant = localDateTime.atZone(zone).toInstant();
    java.util.Date date = Date.from(instant);
}


// 05. java.time.LocalDate --> java.util.Date
public void LocalDateToUdate() {
    LocalDate localDate = LocalDate.now();
    ZoneId zone = ZoneId.systemDefault();
    Instant instant = localDate.atStartOfDay().atZone(zone).toInstant();
    java.util.Date date = Date.from(instant);
}

// 06. java.time.LocalTime --> java.util.Date
public void LocalTimeToUdate() {
    LocalTime localTime = LocalTime.now();
    LocalDate localDate = LocalDate.now();
    LocalDateTime localDateTime = LocalDateTime.of(localDate, localTime);
    ZoneId zone = ZoneId.systemDefault();
    Instant instant = localDateTime.atZone(zone).toInstant();
    java.util.Date date = Date.from(instant);
}

 

對象列表按屬性分組:

//List 以ID分組 Map<Integer,List<Apple>>
Map<Integer, List<Apple>> groupBy = appleList.stream().collect(Collectors.groupingBy(Apple::getId));

List轉Map:

/**
 * List -> Map
 * 須要注意的是:
 * toMap 若是集合對象有重複的key,會報錯Duplicate key ....
 *  apple1,apple12的id都爲1。
 *  能夠用 (k1,k2)->k1 來設置,若是有重複的key,則保留key1,捨棄key2
 */
Map<Integer, Apple> appleMap = appleList.stream().collect(Collectors.toMap(Apple::getId, a -> a,(k1,k2)->k1));

過濾:

List<Apple> filterList = appleList.stream().filter(a -> a.getName().equals("香蕉")).collect(Collectors.toList());

求和:

BigDecimal totalMoney = appleList.stream().map(Apple::getMoney).reduce(BigDecimal.ZERO, BigDecimal::add);

查找流中最大 最小值

Collectors.maxBy 和 Collectors.minBy 來計算流中的最大或最小值。

Optional<Dish> maxDish = Dish.menu.stream().
      collect(Collectors.maxBy(Comparator.comparing(Dish::getCalories)));
maxDish.ifPresent(System.out::println);
 
Optional<Dish> minDish = Dish.menu.stream().
      collect(Collectors.minBy(Comparator.comparing(Dish::getCalories)));
minDish.ifPresent(System.out::println);

去重

List<Person> unique = appleList.stream().collect(
                collectingAndThen(
                        toCollection(() -> new TreeSet<>(comparingLong(Apple::getId))), ArrayList::new)
        );

數組轉List

使用Stream中的Collector收集器

String[] arrays = new String[]{"a", "b", "c"};
List<String> listStrings = Stream.of(arrays).collector(Collectors.toList());

使用java.util.Arrays工具類中的asList()方法(這個不是Java8中新增的內容):

String[] arrays = new String[]{"a", "b", "c"};
List<String> listStrings = Arrays.asList(arrays);

轉換List爲數組

使用Stream:

String[] ss = listStrings.stream().toArray(String[]::new);

使用List中的toArray()方法

String[] sss = listStrings.toArray(new String[listStrings.size()]);

獲取本機內網地址:

/** 本機IP 列表 */
public static List<String> getLocalIps() {
    List<String> ips = new ArrayList<String>();
    try {
        Enumeration<NetworkInterface> enumeration = NetworkInterface.getNetworkInterfaces();
        while (enumeration.hasMoreElements()) {
            NetworkInterface iface = enumeration.nextElement();
            // filters out 127.0.0.1 and inactive interfaces
            if (iface.isLoopback() || !iface.isUp()) continue;

            Enumeration<InetAddress> inetAddresses = iface.getInetAddresses();
            while (inetAddresses.hasMoreElements()) {
                String ip = inetAddresses.nextElement().getHostAddress();
                // 排除 迴環IP/ipv6 地址
                if (ip.contains(":")) continue;
                if (StringUtils.isNotBlank(ip)) ips.add(ip);
            }
        }
    } catch (SocketException e1) {
        e1.printStackTrace();
    }
    return ips;
}
/** 獲取內網IP */
public static String getLocalIntranetIp() {
    List<String> ips = getLocalIps();
    for (String ip : ips) {
        if (isIntranetIp(ip)) return ip;
    }
    return "";
}

/** 判斷是否爲內網IP
 *  tcp/ip協議中, 專門保留了三個IP地址區域做爲私有地址, 其地址範圍以下:
 *  10.0.0.0/8: 10.0.0.0~10.255.255.255
 *  172.16.0.0/12: 172.16.0.0~172.31.255.255
 *  192.168.0.0/16: 192.168.0.0~192.168.255.255
 */
public static boolean isIntranetIp(String ip) {
    try {
        if (ip.startsWith("10.") || ip.startsWith("192.168.")) return true;
        // 172.16.x.x~172.31.x.x
        String[] ns = ip.split("\\.");
        int ipSub = Integer.valueOf(ns[0] + ns[1]);
        if (ipSub >= 17216 && ipSub <= 17231) return true;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return false;
}
相關文章
相關標籤/搜索