温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

JAVA语言的常用操作

发布时间:2021-09-04 23:10:36 来源:亿速云 阅读:116 作者:chen 栏目:互联网科技

本篇内容主要讲解“JAVA语言的常用操作”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“JAVA语言的常用操作”吧!

求和 最大最小 平均值  分组  去重

list.stream().mapToDouble(User::getHeight).sum()//和
list.stream().mapToDouble(User::getHeight).max()//最大
list.stream().mapToDouble(User::getHeight).min()//最小
list.stream().mapToDouble(User::getHeight).average()//平均值


//List 以ID分组 Map<Integer,List<Apple>>
Map<Integer, List<Apple>> groupBy = appleList.stream().collect(Collectors.groupingBy(Apple::getId));
 
System.err.println("groupBy:"+groupBy);
{1=[Apple{id=1, name='苹果1', money=3.25, num=10}, Apple{id=1, name='苹果2', money=1.35, num=20}], 2=[Apple{id=2, name='香蕉', money=2.89, num=30}], 3=[Apple{id=3, name='荔枝', money=9.99, num=40}]}

import static java.util.Comparator.comparingLong;
import static java.util.stream.Collectors.collectingAndThen;
import static java.util.stream.Collectors.toCollection;
 
// 根据id去重
     List<Person> unique = appleList.stream().collect(
                collectingAndThen(
                        toCollection(() -> new TreeSet<>(comparingLong(Apple::getId))), ArrayList::new)
        );

SpringBoot-读取classpath下文件

// 方法1:获取文件或流
this.getClass().getResource("/")+fileName;
this.getClass().getResourceAsStream(failName);
// 方法2:获取文件
File file = org.springframework.util.ResourceUtils.getFile("classpath:test.txt");
// 方法3:获取文件或流
ClassPathResource classPathResource = new ClassPathResource("test.txt");
classPathResource .getFile();
classPathResource .getInputStream();

// >>>>>>>>>>>>>>>> 下面方法可以读取jar包下文件
假设resources目录下有一个test.txt文件,首先获得当前的类加载器,通过类加载器读取文件。

// 方法1
InputStream io = Thread.currentThread().getContextClassLoader().getResourceAsStream("test.txt");
// 方法2
InputStream io = getClass().getClassLoader().getResourceAsStream("test.txt");
————————————————
版权声明:本文为CSDN博主「东京易冷」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/weixin_38229356/article/details/80783142


SpringBoot 项目将项目打包成jar包,使用ClassPathResource时使用的是绝对路径,直接调用getFile()方法会报FileNotFoundException

val resource = ClassPathResource("my.keystore")
val temp = Files.createTempFile("my.keystore", "tmp")
Files.copy(resource.inputStream, temp, StandardCopyOption.REPLACE_EXISTING)
————————————————
版权声明:本文为CSDN博主「bannerXu」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/qq_31724483/article/details/89291739

bean validation 常用的注解 (https://www.cnblogs.com/mr-yang-localhost/p/7812038.html)

 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方法的区别。

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

到此,相信大家对“JAVA语言的常用操作”有了更深的了解,不妨来实际操作一番吧!这里是亿速云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI