当前位置: 首页 > 工具软件 > bash-commons > 使用案例 >

Java代码简洁-commons

白才捷
2023-12-01

1.commons-lang3
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
        </dependency>
1.1 StringUtils

1.判断是否为空 null/“”/" "

String str = " ";
System.out.println(StringUtils.isBlank(str));//true
//判断不是空
System.out.println(StringUtils.isNotBlank(str));//fasle
1.2 NumberUtils
//判断一个参数是不是数字
//isDigits,只能包含整数
//isParsable:整数,小数都可,不能识别正负
//isCreatable可以识别整数,浮点数,正负号,进制
String str = "12.3aa";
System.out.println(NumberUtils.isDigits(str));//false
System.out.println(NumberUtils.isParsable(str));//false
System.out.println(NumberUtils.isCreatable(str));//false
String str1 = "12.3";
System.out.println(NumberUtils.isDigits(str1));//false
System.out.println(NumberUtils.isParsable(str1));//true
System.out.println(NumberUtils.isCreatable(str1));//true
String str2 = "12";
System.out.println(NumberUtils.isDigits(str2));//true
System.out.println(NumberUtils.isParsable(str2));//true
System.out.println(NumberUtils.isCreatable(str2));//true
String str3 = "+12";
System.out.println(NumberUtils.isDigits(str3));//false
System.out.println(NumberUtils.isParsable(str3));//false
System.out.println(NumberUtils.isCreatable(str3));//true
String str4 = "09";
System.out.println(NumberUtils.isDigits(str4));//true
System.out.println(NumberUtils.isParsable(str4));//true
System.out.println(NumberUtils.isCreatable(str4));//false--8进制
1.3 ObjectUtils
1.取第一个不为空的对象
String str1 = null;
String str2 = null;
String str3 = "  ";
String str4 = "数字";
System.out.println(ObjectUtils.firstNonNull(str1,str2,str3,str4));//str3
1.3 ArrayUtils
1.判断数组是否为空
Integer[] ints = new Integer[1];
Integer[] ints1 = new Integer[0];
Integer[] ints2 = new Integer[]{};
Integer[] ints3 = null;
System.out.println(ArrayUtils.isEmpty(ints));//false
System.out.println(ArrayUtils.isEmpty(ints1));//true
System.out.println(ArrayUtils.isEmpty(ints2));//true
System.out.println(ArrayUtils.isEmpty(ints3));//true
2.打印数组内容,向数组中添加内容
Integer[] ints = new Integer[1];
ints[0] = 3;
//ArrayUtils.toString打印数组内容
System.out.println(ArrayUtils.toString(ints));//{3}
//添加数据,新创建一个数组
Integer[] ints1 = ArrayUtils.add(ints, 7);
System.out.println(ArrayUtils.toString(ints1));//{3,7}
2.commons-collections4
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-collections4</artifactId>
            <version>4.3</version>
        </dependency>
2.1 CollectionUtils
1.判断集合是否为空
List<Object> list = new ArrayList<>();
System.out.println(CollectionUtils.isEmpty(list));
Set<Object> set = new TreeSet<>();
System.out.println(CollectionUtils.isNotEmpty(set));

Map<Object, Object> hashMap = new HashMap<>();
System.out.println(MapUtils.isEmpty(hashMap));
System.out.println(MapUtils.isNotEmpty(hashMap));
//获取map中key为a的值,并转为integer
System.out.println(MapUtils.getInteger(hashMap, "a"));
2.获取交集,并集,差集
List<Object> list = new ArrayList<>();
list.add("a");
list.add("b");
list.add("c");

List<Object> list1 = new ArrayList<>();
list1.add("1");
list1.add("2");
list1.add("c");

//交集
System.out.println(CollectionUtils.intersection(list, list1));//[c]
//并集
System.out.println(CollectionUtils.union(list, list1));//[a, 1, b, 2, c]
//差集
System.out.println(CollectionUtils.subtract(list, list1));//[a, b]
System.out.println(CollectionUtils.subtract(list1, list));//[1, 2]
3.commons-io
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-io</artifactId>
            <version>1.3.2</version>
        </dependency>
3.1 FileUtils
1.将文件内容转成字符串读出
String path = "D:\\java\\idea\\IdeaProject2\\utils-demo\\src\\main\\resources\\1.txt";
String file = FileUtils.readFileToString(new File(path), String.valueOf(StandardCharsets.UTF_8));
2.文件内容分行读出
List list = FileUtils.readLines(new File(path), String.valueOf(StandardCharsets.UTF_8));
3.2 FilenameUtils
3.获取文件的baseName/获取文件的后缀
String path = "D:\\java\\idea\\IdeaProject2\\utils-demo\\src\\main\\resources\\1.txt";
System.out.println(FilenameUtils.getBaseName(path));
System.out.println(FilenameUtils.getExtension(path));
4.guava
        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>29.0-jre</version>
        </dependency>
4.1 Joiner
1.Joiner:把集合/数组/可变参数,通过指定的分隔符连接成字符串
List<Object> list = new ArrayList<>();
list.add("a");
list.add("b");
list.add("c");
list.add(null);
//忽略null
Joiner on = Joiner.on(",")skipNulls();//忽略null
System.out.println(on.join(list));//a,b,c
Joiner on = Joiner.on(",").useForNull("null替代");//替换null
System.out.println(on.join(list));//a,b,c,null替代
2.Splitter:通过指定的分隔符把字符串转为集合
String str = "a,b,\"\",  ,   c";
//on指定字符串的分隔符
Splitter on1 = Splitter.on(",");
Iterable<String> split = on1.split(str);
System.out.println(split);//[a, b, "",   ,    c]
//过滤空白的字符串,不包括""
Splitter on2 = Splitter.on(",").omitEmptyStrings();
Iterable<String> split1 = on2.split(str);
System.out.println(split1);//[a, b, "",   ,    c]
//.trimResults空格不保留
Splitter on3 = Splitter.on(",").omitEmptyStrings().trimResults();
Iterable<String> split2 = on3.split(str);
System.out.println(split2);//[a, b, "", c]
//转数组
Iterable<String> split3 = on3.splitToList(str);
System.out.println(split3);//[a, b, "", c]
4.2 CaseFormat
1.下划线和驼峰命名法互转
String str = "student_name";
System.out.println(CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, str));//studentName
System.out.println(CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, str));//StudentName

String str1 = "studentName";
System.out.println(CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, str1));//student_name
4.3 Lists/Sets/Maps
1.快速创建ArrayList并添加数据
List<Object> list = new ArrayList<>();
list.add("a");
list.add("b");
list.add("c");
//提供集合的快速创建方式
List<String> list1 = Lists.newArrayList("a", "b", "c","d");
// Set<String> hashSet = Sets.newHashSet("a", "b", "c","d");

2.把list2分成小的集合,小的集合的大小是size
List<List<String>> lists = Lists.partition(list1, 2);
System.out.println(lists);//[[a, b], [c, d]]
4.4 Ints/Longs/…
1.创建一个Integer类型的集合,并添加数据
List<Integer> list = Ints.asList(1, 2, 3);
System.out.println(list);//[1, 2, 3]
4.5 Multiset
* Multiset--可以放重复元素
* List:元素可重复的有序集合
* set:元素不可重复的无序集合
HashMultiset<String> multiset = HashMultiset.create();
   multiset.add("a");
   multiset.add("b");
   multiset.add("c");
   multiset.add("a");
System.out.println(multiset);//[a x 2, b, c]
//各个元素出现的次数
Set<Multiset.Entry<String>> entries = multiset.entrySet();
 for (Multiset.Entry<String> entry : entries) {
    System.out.println("元素"+entry.getElement()+",个数:"+entry.getCount());
    }   
System.out.println(multiset.entrySet());//[a x 2, b, c]
System.out.println(multiset.elementSet());//[a, b, c]
4.6 HashMultiMap
*HashMultiMap用来替代jdk原生的Map<String,Collection<String>> map
Multimap<String, String> multimap = HashMultimap.create();
multimap.put("a", "1");
multimap.put("b", "2");
Collection<String> a = multimap.get("a");
System.out.println(multimap);//{a=[1], b=[2]}
System.out.println(a);//[1]
//是否包含key=a,value=1的entry
System.out.println(multimap.containsEntry("a", "1"));

//转换成jdk原生api实现的数据结构
Map<String, Collection<String>> map = multimap.asMap();
System.out.println(map);//{a=[1], b=[2]}
4.7 ImmutableList
*不可变集合
List<String> list = new ArrayList<>();
list.add("aa");
list.add("bb");
//不可变集合
ImmutableList<Object> list1 = ImmutableList.builder().add("aa").build();
//list1.add("cc");报错不可添加
Collection<String> collection = Collections.unmodifiableCollection(list);
//collection.add("cc");报错不可添加
list.add("cc");//但是源头可添加--哈哈哈
System.out.println(collection);
4.8 Preconditions
*参数为空,抛出异常
 String param = null;
        Integer param1 = 4;
    //if(param == null){
    //throw  new RuntimeException("参数不可为空!");
    //}
    Preconditions.checkNotNull(param,"参数不能为空");
    //表达式为fasle抛出异常
   Preconditions.checkArgument(param1 <=5,"参数大于5");
5.1FileCopyUtils
FileCopyUtils,文件复制不用关心流关闭
//获取类路径下的资源
ClassPathResource resource = new ClassPathResource("files/1.txt");
//设置编码
EncodedResource encodedResource = new EncodedResource(resource, StandardCharsets.UTF_8);
String targetPath = "D:\\java\\idea\\IdeaProject2\\utils-demo\\src\\main\\resources\\files\\2.txt";
//复制文件1的内容到文件2
FileCopyUtils.copy(encodedResource.getInputStream(),new FileOutputStream(targetPath));

 类似资料: