JAVA日常操作

bigDecimal转字符串的三种表示方式:

本文介绍BigDecimal的3个toString方法的区别。

BigDecimal类有3个toString方法,分别是toEngineeringString、toPlainString和toString,

从BigDecimal的注释中可以看到这3个方法的区别:

toEngineeringString:有必要时使用工程计数法。工程记数法是一种工程计算中经常使用的记录数字的方法,与科学技术法类似,但要求10的幂必须是3的倍数

toPlainString:不使用任何指数

toString:有必要时使用科学计数法

 不使用指数科学记数法工程记数法
27002.7 × 10³2.7 × 10³
270002.7 × 10⁴27 × 10³
2700002.7 × 10⁵270 × 10³
27000002.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()方法为:

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;
}

 

 

 

 

 

 

转载于:https://my.oschina.net/u/1024107/blog/3078416

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值