Day-06 java API 上

一、字符串类

1.1 字符串的初始化

  1. 使用字符串常量直接初始化一个String对象
String s1 = "abc";
  1. 使用String类的构造方法初始化String对象
方法功能描述
String()创建一个内容为空的字符串
String (String value)根据指定的字符串内容创建对象
String (char[] value)根据指定的字符数组创建对象
String (byte[] bytes)根据指定的字节数组创建对象
public class Demo01 {
    public static void main(String[] args) {
        // 根据字符串常量创建字符串对象
        String s1 = "135";
        // 根据字符串无参构造方法创建字符串对象
        String s2 = new String();
        // 根据字符串参数构造方法创建字符串对象
        String s3 = new String("426");
        // 根据字符数组参数构造方法创建字符串对象
        String s4 = new String(new char[]{'7', '5', '1'});
        // 根据字节数组参数构造方法创建字符串对象
        String s5 = new String(new byte[]{9, 5, 3});
    }
}

1.2 String类常见操作

方法名功能
boolean startsWith (String prefix)判断此字符串是否以指定的字符串开始
boolean endsWith (String suffix)判断此字符串是否以指定的字符串结尾
boolean contains (CharSequence cs)判断此字符串是否包含指定的字符串
boolean equals (Object object)将此字符串与指定的字符串比较
int length ()返回此字符串的长度
boolean isEmpty ()判断字符串长度是否为0
public class Demo02 {
    public static void main(String[] args) {
        String s = "abcdefg";
        System.out.println(s); // abcdefg
        System.out.println("字符串长度为:" + s.length());
        System.out.println("字符串是否以”ab“开头:" + s.startsWith("ab")); // 字符串是否以”ab“开头:true
        System.out.println("字符串是否以”fg“结尾:" + s.endsWith("fg")); // 字符串是否以”fg“结尾:true
        System.out.println("字符串是否包含”cde“结尾:" + s.contains("cde")); // 字符串是否包含”cde“结尾:true
        System.out.println("字符串是否包含为”abcd“:" + s.equals("abcd")); // 字符串是否包含为”abcd“:false
        System.out.println("字符串长度是否为0:" + s.isEmpty()); // 字符串长度是否为0:false
    }
}

1.2.1 获取索引

方法名功能
int indexOf (int ch)返回指定字符 ch 在字符串中第一次出现位置的索引
int lastIndexOf (int ch)返回指定字符 ch 在字符串中最后一次出现位置的索引
int indexOf (String str)返回指定子字符串 str 在字符串中第一次出现位置的索引
int lastIndexOf (String str)返回指定子字符串 str 在字符串中最后一次出现位置的索引
char charAt (int index)返回字符串中 index位置上的字符
public class Demo03 {
    public static void main(String[] args) {
        String s = "abcdefgcdefg";
        System.out.println(s); // abcdefgcdefg
        System.out.println("字符串中‘c’字符出现第一次的索引:" + s.indexOf('c')); // 字符串中‘c’字符出现第一次的索引:2
        System.out.println("字符串中‘c’字符出现最后一次的索引:" + s.lastIndexOf('c')); // 字符串中‘c’字符出现最后一次的索引:7
        System.out.println("字符串中”cd“字符串出现第一次的索引:" + s.indexOf("cd")); // 字符串中”cd“字符串出现第一次的索引:2
        System.out.println("字符串中“cde”字符串出现第一次的索引:" + s.lastIndexOf("cde")); // 字符串中“cde”字符串出现第一次的索引:7
        System.out.println("字符串中索引为5的字符为:" + s.charAt(5)); // 字符串中索引为5的字符为:f
    }
}

1.2.2 字符串转换

方法名功能
static String valueOf (int i)将int变量i转换成字符串
String toLowerCase ()使用默认语言环境的规则将 String 中的所有字符都转换为小写字母
String toUpperCase ()使用默认语言环境的规则将 String 中的所有字符都转换为大写字母
char[] toCharArray ()将字符串转换为字符数组
public class Demo04 {
    public static void main(String[] args) {
        String s = "aBcDefGcdEfg";
        System.out.print("转化为字符数组:"); // abcdefgcdefg
        char[]c1 =  s.toCharArray();
        for(int i = 0; i < c1.length; i++){
            System.out.print(c1[i] + " ");
        }
        System.out.print('\n');
        System.out.println("int转化为String:" + String.valueOf(12)); // 字符串中‘c’字符出现第一次的索引:2
        System.out.println("字符串字母转化为小写:" + s.toLowerCase()); // 字符串中‘c’字符出现最后一次的索引:7
        System.out.println("字符串字母转化为大写:" + s.toUpperCase()); // 字符串中”cd“字符串出现第一次的索引:2
    }
}

1.2.3 字符串替换与去除空格

方法名功能
String replace (CharSequence oldstr, CharSequence newstr)返回一个新的字符串,它是通过用 newstr 替换此字符串中出现的所有 oldstr 得到的
String trim ()返回一个新字符串,它去除了原字符串收尾的空格
public class Demo05 {
    public static void main(String[] args) {
        String s = " abcd efg cde fg ";
        System.out.println(s); // ” abcd efg cde fg “
        System.out.println("将“efg”转化为“EFG”:" + s.replace("efg", "EFG")); // 将“efg”转化为“EFG”: abcd EFG cde fg 
        System.out.println("去除字符串首尾两端空格:" + s.trim()); // 去除字符串首尾两端空格:abcd efg cde fg
        System.out.println("去除字符串所有空格:" + s.replace(" ", "")); // 去除字符串所有空格:abcdefgcdefg
    }
}

1.2.4 字符串的截取与分割

方法名功能
String substring (int beginIndex)返回一个新字符串,它包含指定的 beginIndex 处开始,直到此字符串末尾的所有字符
String substring (int beginIndex, int endIndex)返回一个新字符串,它包含指定的beginIndex处开始,直到索引 endIndex - 1 处的所有字符
String [] split (String regex)根据参数 regex 将原来的字符串分割为若干子字符串
public class Demo06 {
    public static void main(String[] args) {
        String s1 = "abc-def-ghi";
        System.out.println(s1); // abc-def-ghi
        System.out.println("从第3个字符截取到末尾:" + s1.substring(2)); // 从第3个字符截取到末尾:c-def-ghi
        System.out.println("从第3个字符截取到第7个字符:" + s1.substring(2, 6)); // 从第3个字符截取到第7个字符:c-de
        System.out.print("通过‘-’分割的字符数串组依次为:");
        String [] s2 = s1.split("-");
        for(int i = 0; i < s2.length; i++){
            System.out.print(s2[i] + " ");
        }
        // 通过‘-’分割的字符数串组依次为:abc def ghi
    }
}

1.3 StringBuffer类

因为字符串是常量,其一旦创建,内容与长度都是不可改变的,所以要对一个字符串进行修改,就只能创建一个新的字符串

但通过StringBuffer类可以对字符串进行修改,可以将StringBuffer类视作字符容器,其长度与内容都是可以改变的

方法名功能
StringBuffer append (char c)添加参数到 StringBuffer 对象中
StringBuffer insert (int offset, String str)在字符串中的offset位置插入字符串 str
StringBuffer deleteCharAt (int index)删除此序列指定位置的字符
StringBuffer delete (int strart, int end)删除 StringBuffer 对象中指定范围内的字符或字符串序列
StringBuffer replace (int strart, int end, String s)在 StringBuffer 对象中替换指定的字符或字符串序列
void setCharAt (int index, char ch)修改指定位置 index 处的字符序列
String toString ()返回 StringBuffer 缓冲区的字符串
StringBuffer reverse ()将此字符序列用其反转形式取代
public class Demo07 {
    public static void main(String[] args) {
        StringBuffer sb1 = new StringBuffer();
        sb1.append("abcdef");
        System.out.println(sb1); // abcdef

        sb1.insert(3, "abc"); // 在”c“后插入”abc“
        System.out.println(sb1); // abcabcdef

        sb1.delete(3,7); // 删除”def“
        System.out.println(sb1); // abcef

        sb1.delete(0, sb1.length()); // 清空缓冲区
        System.out.println(sb1); // (输出空行)

        sb1.append("abcdef");
        System.out.println(sb1); // abcdef
        sb1.setCharAt(3,'D');
        System.out.println(sb1); // abcDef

        sb1.replace(3, 6,"dEEFF"); // 将”Def“替换为”dEEFF“
        System.out.println(sb1); // abcdEEFF
    }
}

1.4 StringBuild类

对字符串进行修改,也可使用StringBuild类,但其与StringBuffer类最大的不同就是StringBuild类是非线程安全的,也就是说StringBuffer类不能被同步访问,但StringBuild类可以

  • 在尝试创建可变字符串,且不要求线程安全(或者不要求多线程)的情况下,尽量使用StringBuild类

StringBuild类方法类似于StringBuffer类

public class Demo08 {
    public static void main(String[] args) {
        StringBuilder sb1 = new StringBuilder();
        sb1.append("abcdef");
        System.out.println(sb1); // abcdef

        sb1.insert(3, "abc"); // 在”c“后插入”abc“
        System.out.println(sb1); // abcabcdef

        sb1.delete(3,7); // 删除”def“
        System.out.println(sb1); // abcef

        sb1.delete(0, sb1.length()); // 清空缓冲区
        System.out.println(sb1); // (输出空行)

        sb1.append("abcdef");
        System.out.println(sb1); // abcdef
        sb1.setCharAt(3,'D');
        System.out.println(sb1); // abcDef

        sb1.replace(3, 6,"dEEFF"); // 将”Def“替换为”dEEFF“
        System.out.println(sb1); // abcdEEFF
    }
}

二、System类与Runtime类

2.1 System类

System类定义了一些与系统相关的属性与方法

方法名功能
static void exit (int status)该方法用于终止当前正在运行的 java 虚拟机,其中参数 status 表示状态码,若状态码非0,则表示异常终止
static void gc ()运行垃圾回收器,用于对垃圾进行回收
static void currentTimeMillis ()返回以毫秒为单位的当前时间
static void arraycopy(Object src, int srcPos, Object dest, intdestPos, int length)从 src 引用的指定源数组复制到 dest 引用的数组,复制从指定位置开始,到目标数组的指定位置结束
static Properties getProperties ()取得当前系统的属性
static String getProperty (String key)获取指定键描述的系统属性

2.1.1 arraycopy () 方法

arraycopy () 方法用于将数组从源数组复制到目标数组

public class Demo09 {
    public static void main(String[] args) {
        // 创建数组并打印
        int [] srcArray = {5, 1, 3, 7, 9, 8, 6, 2, 4};
        printArray(srcArray); // 5 1 3 7 9 8 6 2 4
        System.out.print('\n');
        int [] newArray = {4, 5, 9, 7, 1, 3};
        printArray(newArray); // 4 5 9 7 1 3
        System.out.print('\n');

        // 在新数组中复制源数组元素
        System.arraycopy(srcArray, 5, newArray, 2, 4);

        // 再次打印
        printArray(srcArray); // 5 1 3 7 9 8 6 2 4
        System.out.print('\n');
        printArray(newArray); // 4 5 8 6 2 4
    }
    public static void printArray(int [] a){
        for(int i = 0; i < a.length; i++){
            System.out.print(a[i] + " ");
        }
    }
}

2.1.2 currentTimeMilis () 方法

currentTimeMilis () 方法用于获取当前系统的时间,返回值为 long 类型,返回值表示当前时间与1970年1月1日0点0分0秒之间的时间差

public class Demo10 {
    public static void main(String[] args) {
        // 开始时间
        long startTime = System.currentTimeMillis();
        int sum = 0;
        for (int i = 0; i < 10000000; i++){
            sum +=1 ;
        }
        // 结束时间
        long endTime = System.currentTimeMillis();
        System.out.println("程序运行时间:" + (endTime - startTime) + "毫秒");
    }
}

2.1.3 getProperties () 和 getProperty () 方法

  • getProperties ()方法用于获取当前系统全部属性,返回值类型为 Properties,返回对象中封装了系统的所有属性
  • getProperty () 方法用于根据系统属性名称获取对应的属性值
public class Demo11 {
    public static void main(String[] args) {
        // 获取当前同属性
        Properties properties = System.getProperties();

        // 获取所有系统属性的key,返回Enumeration对象
        Enumeration propertyNames = properties.propertyNames();

        while(propertyNames.hasMoreElements()){
            // 获取系统属性的key
            String key = (String) propertyNames.nextElement();
            // 获取当前key对应的value
            String value = System.getProperty(key);
            System.out.println(key + "->" + value);
        }

    }
}

2.1.4 gc()方法

在java中,当一个对象成为垃圾时会占用内存空间,通过java的垃圾回收机制,java虚拟机会自动回收垃圾对象占用的空间

除了java虚拟机启动垃圾回收器将垃圾对象从内存中释放外,我们也可手动调用 System.gc () 方法进行垃圾回收

public class Demo12 {
    public static void main(String[] args) {
        Test t1 = new Test();
        Test t2 = new Test();
        t1 = null;
        t2 = null;
        System.gc();
    }
}
class Test{
    public void finalize(){
        System.out.println("垃圾对象回收");
    }
}

2.2 Runtime类

Runtime 类用来表示虚拟机运行的状态,用于封装java虚拟机进程

Runtime类属于单例类,有且只有一个实例,因此在定义Runtime类的时候,它的构造方法已经私有化了,同时对象不可实例化,

  • 单例类是一种设计模式,它确保一个类只有一个实例,并提供全局访问点来获取该实例。在单例模式中,类的构造函数被私有化,以防止其他代码直接实例化该类。而通过提供一个静态方法或静态变量来获取类的唯一实例。

若想获得一个Runtime实例,只能通过以下方式

Runtime run = Runtime.getRuntime();
方法功能
getRuntime ()该方法用于返回当前应用程序的运行环境对象
exec (String command)该方法用于根据指定的路径执行对应的可执行文件
freeMemory ()该方法用于返回java虚拟机中的空闲内存量,以字节为单位
maxMemory ()该方法用于返回java虚拟机的最大可用内存量
availableProcessors ()该方法用于返回当前虚拟机的处理器个数
totalMemory ()该方法用于返回java虚拟机中的内存总量
// 获取当前虚拟机信息
public class Demo13 {
    public static void main(String[] args) {
        //获取Runtime实例对象
        Runtime rt = Runtime.getRuntime();
        System.out.println("处理器个数:" + rt.availableProcessors());
        System.out.println("空闲内存容量:" + rt.freeMemory() / 1024 / 1024 + "M");
        System.out.println("最大可用内存容量:" + rt.maxMemory() / 1024 / 1024 + "M");
        System.out.println("虚拟机中内存总量:" + rt.totalMemory() / 1024 / 1024 + "M");
    }
}
// 操作系统进程
public class Demo14 {
    public static void main(String[] args) throws IOException {
        //获取Runtime实例对象
        Runtime rt = Runtime.getRuntime();

        rt.exec("notepad.exe");
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,以下是一个简单的ElasticSearch聚合的Java API示例: ```java import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.client.Client; import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.search.aggregations.AggregationBuilders; import org.elasticsearch.search.aggregations.bucket.histogram.DateHistogramInterval; import org.elasticsearch.search.aggregations.bucket.histogram.Histogram; import org.elasticsearch.search.aggregations.bucket.terms.Terms; import org.elasticsearch.search.aggregations.metrics.sum.Sum; import org.elasticsearch.search.aggregations.metrics.valuecount.ValueCount; import static org.elasticsearch.index.query.QueryBuilders.rangeQuery; public class ElasticSearchAggregationExample { public static void main(String[] args) { // 创建ElasticSearch客户端 Client client = // ...; // 构建查询条件 QueryBuilder query = QueryBuilders.boolQuery() .must(rangeQuery("timestamp").gte("2022-01-01T00:00:00").lte("2022-01-31T23:59:59")); // 构建聚合条件 AggregationBuilder aggregation = AggregationBuilders .dateHistogram("sales_over_time") .field("timestamp") .dateHistogramInterval(DateHistogramInterval.DAY) .subAggregation( AggregationBuilders .terms("product_types") .field("product_type") .subAggregation( AggregationBuilders.sum("total_sales").field("sales"), AggregationBuilders.count("transaction_count").field("transaction_id") ) ); // 执行查询 SearchResponse response = client.prepareSearch("my_index") .setQuery(query) .addAggregation(aggregation) .execute() .actionGet(); // 解析聚合结果 Histogram histogram = response.getAggregations().get("sales_over_time"); for (Histogram.Bucket bucket : histogram.getBuckets()) { System.out.println("Date: " + bucket.getKeyAsString()); Terms productTypes = bucket.getAggregations().get("product_types"); for (Terms.Bucket productType : productTypes.getBuckets()) { System.out.println("Product Type: " + productType.getKeyAsString()); Sum totalSales = productType.getAggregations().get("total_sales"); System.out.println("Total Sales: " + totalSales.getValue()); ValueCount transactionCount = productType.getAggregations().get("transaction_count"); System.out.println("Transaction Count: " + transactionCount.getValue()); } } // 关闭客户端 client.close(); } } ``` 这个示例通过ElasticSearch的Java API执行了一个聚合,其中包含了两层嵌套聚合,分别按照日期和产品类型对销售数据进行了汇总,输出了每个日期和产品类型的销售总额和交易次数。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值