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;
}
相关文章
相关标签/搜索