Java代码常用功能实现总结

目录

1.获取当前系统时间:

2.获取当前时间戳:

3.获取主机名和IP

4.new String用法:

5.ByteBuffer和String的互相转换:

6.int和string相互转换:

7.把多个json放到list中:

8.List集合去除重复数据:

9.遍历Map的四种方法

10.除去字符串(String)中的换行字符(\r \n \t):

11.System.getProperty("属性名")方法的使用:

12.获取昨天,上个星期一,本月开始时间:

13.概率实现:

1.获取当前系统时间:
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式

System.out.println(df.format(new Date()));

运行结果:

2017-10-22 12:18:37

(1)时间戳(精确到秒为10位)转换为日期格式:

df.format(new Date(Long.valueOf(1538209477+"000")))

(2)日期格式转换为时间戳:

String.valueOf(df.parse("2018-09-29 16:27:42").getTime())

 

2.获取当前时间戳:
-------------------------------------------
(1)方法 一
System.currentTimeMillis();
(2)方法 二
Calendar.getInstance().getTimeInMillis();
(3)方法 三
new Date().getTime();
补充:获取时间戳三种方法执行效率比较


import java.util.Calendar;
import java.util.Date;
 
public class TimeTest {
    private static long _TEN_THOUSAND=10000;
    public static void main(String[] args) {
        long times=1000*_TEN_THOUSAND;
        long t1=System.currentTimeMillis();
        testSystem(times);
        long t2=System.currentTimeMillis();
        System.out.println(t2-t1);
 
        testCalander(times);
        long t3=System.currentTimeMillis();
        System.out.println(t3-t2);
 
        testDate(times);
        long t4=System.currentTimeMillis();
        System.out.println(t4-t3);
    }
 
    public static void testSystem(long times){
        for(int i=0;i<times;i++){
            long currentTime=System.currentTimeMillis();
        }
    }
 
    public static void testCalander(long times){
        for(int i=0;i<times;i++){
            long currentTime=Calendar.getInstance().getTimeInMillis();
        }
    }
 
    public static void testDate(long times){
        for(int i=0;i<times;i++){
            long currentTime=new Date().getTime();
        }
    }
 
}
执行结果:
43
1885
45
Calendar.getInstance().getTimeInMillis() 这种方式速度最慢,这是因为Canlendar要处理时区问题会耗费较多的时间。
Python:

import time
print (time.time())
print(int(round(time.time()*1000)))
print(int(time.time()))
运行结果:

1513776456.43
1513776456440
1513776456
疑惑:java上面的三种方法获取的时间戳都是13位的,而python用自带的time模块获取的却是1513776456.43,还得自己转换成10位或13位的

解答:时间戳的位数是根据算法计算的,没有固定的位数。 可信时间戳计算出来的电子文件的数字指纹是40位~
由于精度不同,导致长度不一致,直接转换错误。 JAVA时间戳长度是13位,如:1294890876859 PHP时间戳长度是10位(不知道js默认是多少位,但是在工作中python传给js的时间戳还必须是13位,10位的解析不出来), 如:1294890859 php echo date!

 

3.获取主机名和IP
-------------------------------------------
InetAddress a=InetAddress.getLocalHost();
String localname=a.getHostName();
String localip=a.getHostAddress();
System.out.println("本机名称是:" + localname);
System.out.println("本机的ip是 :" + localip);
System.out.println(InetAddress.getLocalHost());
运行结果:
本机名称是:h66
本机的ip是 :192.168.205.66
h66/192.168.205.66

 

4.new String用法:
byte[] bytes = "hui".getBytes(); //String转bytes
String receiveText = new String( bytes,1,2); //bytes转String
System.out.println(receiveText);

运行结果:

ui

 

5.ByteBuffer和String的互相转换:
String hui = "hehe";
ByteBuffer buffer = ByteBuffer.wrap(hui.getBytes());
Charset charset = Charset.forName("UTF-8");
CharsetDecoder decoder = charset.newDecoder();
CharBuffer charBuffer = decoder.decode(buffer.asReadOnlyBuffer());
System.out.println(buffer);
System.out.println(charBuffer.toString());

运行结果:

java.nio.HeapByteBuffer[pos=0 lim=4 cap=4]
hehe

 

6.int和string相互转换:
-------------------------------------------
int -> String:
int i=12345;
String s="";
第一种方法:s=i+"";
第二种方法:s=String.valueOf(i);
String -> int或long:
s="12345";
int i;
第一种方法:i=Integer.parseInt(s);或Long.parseInt(s)
第二种方法:i=Integer.valueOf(s).intValue();或Long.valueOf(s).longValue()
这两种方法有什么区别呢?作用是不是一样的呢?是不是在任何下都能互换呢?答:
第一种方法:s=i+""; //会产生两个String对象
第二种方法:s=String.valueOf(i); //直接使用String类的静态方法,只产生一个对象
第一种方法:i=Integer.parseInt(s);//直接使用静态方法,不会产生多余的对象,但会抛出异常
第二种方法:i=Integer.valueOf(s).intValue();//Integer.valueOf(s) 相当于 new Integer(Integer.parseInt(s)),也会抛异常,但会多产生一个对象

 

7.把多个json放到list中:
        List<String> keysList1 = new ArrayList<>();
        JSONObject json1 = new JSONObject();
        json1.put("littleTitle", "你爱谁");
        json1.put("text", "小强签名设计");
        keysList1.add(json1.toString());
        JSONObject json2 = new JSONObject();
        json2.put("littleTitle", "我爱谁");
        json2.put("text", "你猜");
        keysList1.add(json2.toString());
        System.out.println("keysList11-->"+keysList1);
运行结果:

keysList11-->[{"littleTitle":"你爱谁","text":"小强签名设计"}, {"littleTitle":"我爱谁","text":"你猜"}]

 

8.List集合去除重复数据:
import java.util.*;
 
@SuppressWarnings({ "rawtypes", "unchecked" })
public class printt {
    public static void main(String[] args) {
        List<String> strs = new ArrayList<String>();
        String str2 = "world";
        String str1 = "hello";
        String str3 = "world";
        strs.add(str1);// 通过add方法
        strs.add(str2);
        strs.add(str3);
        System.out.println(removeDuplicate(strs));
        System.out.println(removeDuplicate1(strs));
        System.out.println(removeDuplicate3(strs));
        removeDuplicate4(strs);
 
        // 可用于效率测试
        final List<String> list = new ArrayList<String>();
        for (int i = 0; i < 1000; i++) {
            list.add("haha-" + i);
        }
 
        long time = System.currentTimeMillis();
        for (int i = 0; i < 10000; i++) {
            removeDuplicate2(list);
        }
        long time1 = System.currentTimeMillis();
        System.out.println("time1:" + (time1 - time));
    }
 
    public static List removeDuplicate(List list) {
        for (int i = 0; i < list.size() - 1; i++) {
            for (int j = list.size() - 1; j > i; j--) {
                if (list.get(j).equals(list.get(i))) {
                    list.remove(j);
                }
            }
        }
        return list;
    }
 
    // 利用HashSet不能添加重复数据的特性
    public static List removeDuplicate1(List<String> list) {
        // 如果对list添加顺序无要求则可直接用
        // HashSet set = new HashSet(list);
        // list.clear();
        // list.addAll(set);
 
        // 如果对list添加顺序有要求的话,由于HashSet不能保证添加顺序,所以只能作为判断条件
        HashSet<String> set = new HashSet<String>();
        List<String> result = new ArrayList<String>();
        for (String str : list) {
            if (set.add(str)) {
                result.add(str);
            }
        }
        list.clear();
        list.addAll(result);
        return list;
    }
 
    // 利用LinkedHashSet不能添加重复数据并能保证添加顺序的特性
    private static void removeDuplicate2(List<String> list) {
        LinkedHashSet<String> set = new LinkedHashSet<String>(list);
        /*
         * 或者: LinkedHashSet<String> set = new LinkedHashSet<String>();
         * set.addAll(list);
         */
        list.clear();
        list.addAll(set);
        // System.out.println(list);
    }
 
    // 利用List的contains方法循环遍历
    public static List removeDuplicate3(List list) {
        List listTemp = new ArrayList();
        for (int i = 0; i < list.size(); i++) {
            if (!listTemp.contains(list.get(i))) {
                listTemp.add(list.get(i));
            }
        }
        return listTemp;
    }
 
    // 删除ArrayList中重复元素,保持顺序
    public static void removeDuplicate4(List list) {
        Set set = new HashSet();
        List newList = new ArrayList();
        for (Iterator iter = list.iterator(); iter.hasNext();) {
            Object element = iter.next();
            if (set.add(element))
                newList.add(element);
        }
        list.clear();
        list.addAll(newList);
        System.out.println(list);
    }
}
运行结果:

[hello, world]
[hello, world]
[hello, world]
[hello, world]
time1:1396

参考:

https://www.cnblogs.com/cainiao-Shun666/p/7911142.html

https://blog.youkuaiyun.com/u012156163/article/details/78338574

 

9.遍历Map的四种方法
(来自http://www.cnblogs.com/kristain/articles/2033566.html)

public static void main(String[] args) {
    Map<String, String> map = new HashMap<String, String>();
    map.put("1", "value1");
    map.put("2", "value2");
    map.put("3", "value3");
      
    //第一种:普遍使用,二次取值
    System.out.println("通过Map.keySet遍历key和value:");
    for (String key : map.keySet()) {
        System.out.println("key= "+ key + " and value= " + map.get(key));
    }
      
    //第二种
    System.out.println("通过Map.entrySet使用iterator遍历key和value:");
    Iterator<Map.Entry<String, String>> it = map.entrySet().iterator();
    while (it.hasNext()) {
        Map.Entry<String, String> entry = it.next();
        System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());
    }
      
    //第三种:推荐,尤其是容量大时
    System.out.println("通过Map.entrySet遍历key和value");
    for (Map.Entry<String, String> entry : map.entrySet()) {
        System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());
    }
 
    //第四种
    System.out.println("通过Map.values()遍历所有的value,但不能遍历key");
    for (String v : map.values()) {
        System.out.println("value= " + v);
    }
}
参考:http://blog.youkuaiyun.com/luanlouis/article/details/43017071

 

10.除去字符串(String)中的换行字符(\r \n \t):
-------------------------------------------
String hui = "'ab cd" + "\n" + "efg'";
System.out.println("转换前:"+hui);
hui = hui.replaceAll("\r|\n", "");
System.out.println("转换后:"+hui);
运行结果:
转换前:'ab cd
efg'
转换后:'ab cdefg'

补充:

例2:
System.out.println("\\r 输出:"+"abc"+"\r"+"abc");
System.out.println("\\n 输出:"+"abc"+"\n"+"abc");
以上两句在控制台输出的格式是一样的:
\r输出:abc
abc
\r输出:abc
abc
 
那么他们有什么区别呢?
例3:
String hui = "'ab cd" + "\n\r" + "efg'";
System.out.println("转换前:"+hui);
hui = hui.replaceAll("\r|\n", "");
System.out.println("转换后:"+hui);
运行结果:
转换前:'ab cd
efg'
转换后:'ab cdefg'
 
可以看出\r表示回车,\n表示另起一行(\r 叫回车 Carriage Return  ;\n 叫新行 New Line)
我们可以再做一个实验:
String hui = "'ab cd" + "\r\n" + "efg'";
System.out.println("转换前:"+hui);
hui = hui.replaceAll("\r|\n", "");
System.out.println("转换后:"+hui);
运行结果:
转换前:'ab cd
efg'
转换后:'ab cdefg'
 
注:
trim()用来去首尾的空格符
\n 换行(\u000a)
\t 水平制表符(\u0009)
\s 空格(\u0008)
\r 回车(\u000d)
11.System.getProperty("属性名")方法的使用:
(参考自:http://blog.youkuaiyun.com/wodewutai17quiet/article/details/68946890)

System.out.println("操作系统的名称:"+System.getProperty("os.name"));    //Windows 8
System.out.println("操作系统的架构:"+System.getProperty("os.arch"));    //amd64
System.out.println("操作系统的版本:"+System.getProperty("os.version"));    //6.2
System.out.println("Java 运行时环境版本:"+System.getProperty("java.version"));    //1.7.0_25
System.out.println("Java 运行时环境供应商:"+System.getProperty("java.vendor"));    //Oracle Corporation
System.out.println("Java 供应商的 URL:"+System.getProperty("java.vendor.url"));    //http://java.oracle.com/
System.out.println("Java 安装目录:"+System.getProperty("java.home"));    //C:\Program Files\Java\jdk1.7.0_25\jre
System.out.println("Java 虚拟机规范版本:"+System.getProperty("java.vm.specification.version"));    //1.7
System.out.println("Java 虚拟机规范供应商:"+System.getProperty("java.vm.specification.vendor"));    //Oracle Corporation
System.out.println("Java 虚拟机规范名称:"+System.getProperty("java.vm.specification.name"));    //Java Virtual Machine Specification
System.out.println("Java 虚拟机实现版本:"+System.getProperty("java.vm.version"));    //23.25-b01
System.out.println("Java 虚拟机实现供应商:"+System.getProperty("java.vm.vendor"));    //Oracle Corporation
System.out.println("Java 虚拟机实现名称:"+System.getProperty("java.vm.name"));    //Java HotSpot(TM) 64-Bit Server VM
System.out.println("Java 运行时环境规范版本:"+System.getProperty("java.specification.version"));    //1.7
System.out.println("Java 运行时环境规范供应商:"+System.getProperty("java.specification.vendor"));    //Oracle Corporation
System.out.println("Java 运行时环境规范名称:"+System.getProperty("java.specification.name"));    //Java Platform API Specification
System.out.println("Java 类格式版本号:"+System.getProperty("java.class.version"));    //51.0
System.out.println("Java 类路径:"+System.getProperty("java.class.path"));
System.out.println("加载库时搜索的路径列表:"+System.getProperty("java.library.path"));
System.out.println("默认的临时文件路径:"+System.getProperty("java.io.tmpdir"));
System.out.println("要使用的 JIT 编译器的名称:"+System.getProperty("java.compiler"));
System.out.println("一个或多个扩展目录的路径:"+System.getProperty("java.ext.dirs"));
System.out.println("文件分隔符(在 UNIX 系统中是“/”):"+System.getProperty("file.separator"));
System.out.println("路径分隔符(在 UNIX 系统中是“:”):"+System.getProperty("path.separator"));
System.out.println("行分隔符(在 UNIX 系统中是“/n”):"+System.getProperty("line.separator"));
System.out.println("用户的账户名称:"+System.getProperty("user.name"));
System.out.println("用户的主目录:"+System.getProperty("user.home"));
System.out.println("用户的当前工作目录:"+System.getProperty("user.dir"));
12.获取昨天,上个星期一,本月开始时间:
        //昨天
        Date date=new Date();//取时间
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(date);
        calendar.add(calendar.DATE,-1);//把日期往后增加一天.整数往后推,负数往前移动
        date=calendar.getTime(); //这个时间就是日期往后推一天的结果
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        String dateString = formatter.format(date);
        System.out.println(dateString);
        
        //上个星期一
//        Calendar cal = Calendar.getInstance();
//        int n = cal.get(Calendar.DAY_OF_WEEK) - 1;
//        if (n == 0) {
//            n = 7;
//        }
//        cal.add(Calendar.DATE, -(7 + (n - 1)));// 上周一的日期
//        Date monday = cal.getTime();
//        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
//        String dateString = formatter.format(monday);
//        System.out.println(dateString);
        
        //本月第一天
//        Calendar cal_1=Calendar.getInstance();//获取当前日期 
//        cal_1.add(Calendar.MONTH, -1);
//        cal_1.set(Calendar.DAY_OF_MONTH,1);//设置为1号,当前日期既为本月第一天
//        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
//        String firstDay = formatter.format(cal_1.getTime());
//        System.out.println(firstDay);
参考:https://zhidao.baidu.com/question/523653874220755605.html

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date nowDate = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(nowDate);
 
        calendar.set(Calendar.DATE, calendar.get(Calendar.DATE) - 1);
        Date updateDate5 = calendar.getTime();
        System.out.println(updateDate5.getTime() + "往前推1天的时间=" + sdf.format(updateDate5));
        System.out.println(updateDate5.getTime() / 1000 + "往前推1天的时间=" + sdf.format(updateDate5));
        Long time = 1537845150178L;
        System.out.println(System.currentTimeMillis() - time < 1 * 24 * 3600 * 1000L);
 
        // 往前推一个月
        calendar.set(Calendar.MONTH, calendar.get(Calendar.MONTH) - 1);
        Date updateDate2 = calendar.getTime();
        System.out.println("往前推1个月的时间" + sdf.format(updateDate2));
        // 往后推13个月
        calendar.set(Calendar.MONTH, calendar.get(Calendar.MONTH) + 13);
        Date updateDate3 = calendar.getTime();
        System.out.println("往后推13个月的时间=" + sdf.format(updateDate3));
        // 往后推一天
        calendar.set(Calendar.DATE, calendar.get(Calendar.DATE) + 1);
        Date updateDate4 = calendar.getTime();
        System.out.println("往后推1天的时间=" + sdf.format(updateDate4));
运行结果:
1537845735819往前推1天的时间=2018-09-25 11:22:15
1537845735往前推1天的时间=2018-09-25 11:22:15
false
往前推1个月的时间2018-08-25 11:22:15
往后推13个月的时间=2019-09-25 11:22:15
往后推1天的时间=2019-09-26 11:22:15

(1)昨天八点到现在:

    public static void main(String[] args) {  
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.HOUR_OF_DAY,8);
        calendar.set(Calendar.MINUTE,0);
        calendar.set(Calendar.SECOND,0);
        calendar.set(Calendar.MILLISECOND,0);
        calendar.add(Calendar.DAY_OF_YEAR,-1);
        Date date = calendar.getTime();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String startTime = sdf.format(date);
        System.out.println("startTime-->"+startTime);
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String endTime = sdf1.format(new Date());
        System.out.println("endTime-->"+endTime);
    }
运行结果:
startTime-->2018-10-09 08:00:00
endTime-->2018-10-10 14:28:04

 

13.概率实现:
(可参考https://www.cnblogs.com/zz-3m23d-begining/p/7767214.html)

public static void main(String[] args) {
    double d = Math.random();//生成一个0~1的随机数
    if(d<=0.5){
        System.out.println("A");//50%概率
    }else if(d<=0.8){
        System.out.println("B");//30%概率
    }else{
        System.out.println("C");//20%概率
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值