java常用快捷操作方法总汇

正则表达式

String base64Header = "data:image/jpeg;base64,11111111111111111111111111111111";
Pattern pattern = Pattern.compile("data:image/.*?;base64,");
Matcher matcher = pattern.matcher(base64Header);
if (matcher.find()) {
    System.out.println(matcher.group(0));
}
String fileName = matcher.replaceAll("");
System.out.println(fileName);

mybatisplu获取对象的表名和字段名

String tableName = SqlHelper.table(Class<?> clazz).getTableName();
List<TableFieldInfo> fieldInfoList = SqlHelper.table(Class<?> clazz).getFieldList();
// 字段名
String column = TableFieldInfo.getColumn();
// 对象属性
String name = TableFieldInfo.getField().getName();

map中key排序

// 升序排序
List<Map.Entry<String, List<DataStorageInfo>>> entryList = batchNumberMap.entrySet().stream()
        .sorted(Map.Entry.comparingByKey()).collect(Collectors.toList());
// 降序排序
List<Map.Entry<String, List<DataStorageInfo>>> entryList = batchNumberMap.entrySet().stream()
        .sorted(Collections.reverseOrder(Map.Entry.comparingByKey())).collect(Collectors.toList());

mysql自动填充创建时间和修改时间

create table test(
  id integer not null auto_increment primary key,
  name varchar(20) not null ,
  create_time timestamp not null default CURRENT_TIMESTAMP COMMENT '创建时间',
  update_time timestamp not null default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP COMMENT '更新时间');

ALTER TABLE test MODIFY create_time timestamp not null default CURRENT_TIMESTAMP COMMENT '创建时间';
ALTER TABLE test MODIFY update_time timestamp not null default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP COMMENT '更新时间';
 
ALTER TABLE test ADD create_time timestamp not null default CURRENT_TIMESTAMP COMMENT '创建时间';
ALTER TABLE test ADD update_time timestamp not null default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP COMMENT '更新时间';

深度复制

Cell clone = SerializationUtils.clone(cell);

sql

wm_concat: Oracle自带的wm_concat()函数将字符串合并
LISTAGG:  
LISTAGG (e.emp_name, ',') WITHIN GROUP (ORDER BY e.emp_name) names
LISTAGG()函数将字符串合并,它的优点在于,合并的连接符号可以指定为任意字符,并且可以很方便实现ORDER BY排序

1.数组转换成字符串

int[] arr = {1,2,3,4};
String str= Arrays.stream(arr).boxed().map(Object::toString).collect(Collectors.joining(","));

2.集合转换成字符串

Integer[] arr = {1,2,3,4};
List<Integer> list = Arrays.asList(arr);
String str = list.stream().map(Object::toString).collect(Collectors.joining(","));
String join = String.join(",", list);

将两个字符数组合并成一个新的字符数组。

List<String> list = Arrays.asList("m,k,l,a", "1,3,5,7");
    List<String> listNew = list.stream().flatMap(s -> {
      // 将每个元素转换成一个stream
      String[] split = s.split(",");
      Stream<String> s2 = Arrays.stream(split);
      return s2;
    }).collect(Collectors.toList());

统计员工人数、平均工资、工资总额、最高工资

// 求总数
    Long count = personList.stream().collect(Collectors.counting());
    // 求平均工资
    Double average = personList.stream().collect(Collectors.averagingDouble(Person::getSalary));
    // 求最高工资
    Optional<Integer> max = personList.stream().map(Person::getSalary).collect(Collectors.maxBy(Integer::compare));
    // 求工资之和
    Integer sum = personList.stream().collect(Collectors.summingInt(Person::getSalary));
    // 一次性统计所有信息
    DoubleSummaryStatistics collect = personList.stream().collect(Collectors.summarizingDouble(Person::getSalary));

3.集合交集、并集、补集、差集

//并集
Collection<String> union = CollectionUtils.union(listA, listB);
System.out.println("并集:"+union);
//交集
Collection<String> intersection = CollectionUtils.intersection(listA, listB);
System.out.println("交集:"+intersection);
//交集的补集
Collection<String> disjunction = CollectionUtils.disjunction(listA, listB);
System.out.println("交集的补集   :"+disjunction);
//差集(集合相减)
Collection<String> subtract = CollectionUtils.subtract(listA, listB);
System.out.println("差集(集合相减)   :"+subtract);

4.list集合分组

// 去掉重复
list.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> 
                    new TreeSet<>(Comparator.comparing(obj::getId))), ArrayList::new))
// 多字段分组
Map<String, List<T>> workflowMapList = t.stream().collect(Collectors.groupingBy(w -> w.getField1().concat(w.getField2())));
// 单子段分组
Map<String, List<T>> workflowMapList = t.stream().collect(Collectors.groupingBy(T::getField1));
// 取其中的某个字段
Map<Integer, String> map = list.stream().collect(Collectors.toMap(Entity::getId, Entity::getType));
// 转换类型
Map<Long, String> map = basCodeDict.stream().collect(Collectors.toMap(o  -> Long.valueOf(o.getValue().toString()), OptionsVo::getText));
Map<String, List<Long>> map = list.stream()
                    .collect(Collectors.groupingBy(Object::getId, Collectors.mapping(Object::getId, Collectors.toList())));


/**
 * List<T> -> Map<Object,T>
 * 需要注意的是:
 * 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<Integer>
Map<Integer, Integer> collect = list.stream().collect(Collectors.toMap(i-> i,Function.identity()))

将list对象中字符拼接字段合并成一个集合
List<String> list = stocks.stream().map(s -> Lists.newArrayList(Arrays.asList(s.getPath().split(","))))
                .flatMap(Collection::stream).distinct().collect(Collectors.toList());

字符串转换成集合
List<String> list = Arrays.stream(value.toString().split(",")).distinct().collect(Collectors.toList());

5.排序

// 默认字符排序
Collections.sort(listStr);
// 对象单个排序
itemList.sort(Comparator.comparing(item::getA));
// 多字段排序:a b 都是对象的属性
itemList.sort(Comparator.comparing(item::getA).thenComparing(item::getB));

//返回 对象集合以类属性一降序排序 注意两种写法
list.stream().sorted(Comparator.comparing(类::属性一).reversed());//先以属性一升序,结果进行属性一降序
list.stream().sorted(Comparator.comparing(类::属性一,Comparator.reverseOrder()));//以属性一降序
// map排序
detailList.sort(Comparator.comparing(item -> item.get(groupField).toString()));

1.  顺序排序 Collections.sort(list);
2.  混乱排序 Collections.shuffle(list);
3.  倒序排序 Collections.reverse(list);

6.字符串操作

// 首字母转成大写
String capitalize = StringUtils.capitalize(str);
// 重复拼接字符串
String str = StringUtils.repeat("ab", 2);

7.commons-beanutils工具方法

// 设置/获取 对象属性
BeanUtils.setProperty(user, "id", 1);
BeanUtils.setProperty(user, "name", "yideng");
System.out.println(BeanUtils.getProperty(user, "name")); // 输出 yideng

// 对象和map转化
Map<String, String> map = BeanUtils.describe(user);
// map转对象
BeanUtils.populate(newUser, map);

8.guava 提供的工具方法

// 反转list
List<Integer> reverse = Lists.reverse(list);
// list集合元素太多,可以分成若干个集合,每个集合10个元素
List<List<Integer>> partition = Lists.partition(list, 10);

9.特殊集合

1 Multimap 一个key可以映射多个value的HashMap
2 BiMap 一种连value也不能重复的HashMap
3 Table 一种有两个key的HashMap
4 Multiset 一种用来计数的Set

10.其他备注

AsyncContext asyncContext = request.startAsync();
asyncContext.start(new Runnable() {});
//异步请求完成通知
//此时整个请求才完成
//其实可以利用此特性 进行多条消息的推送 把连接挂起。。
asyncContext.complete();

11.注解

分布式锁,保证分布式中指只执行一次,EnableSchedulerLock
@EnableSchedulerLock(defaultLockAtMostFor = "PT480S")

12.redis配置主从读写分离

@Bean
public LettuceClientConfigurationBuilderCustomizer configurationBuilderCustomizer(){
    return clientConfigurationBuilder -> clientConfigurationBuilder.readFrom(ReadFrom.REPLICA_PREFERRED);
}
//配置 redisTemplate 优先从 slave 节点读取数据,如果 slave 都宕机了,则抛出异常
        //return clientConfigurationBuilder -> clientConfigurationBuilder.readFrom(ReadFrom.REPLICA);

13.restTemplate 调用nacos中其他服务的接口,不使用Feign

    @LoadBalanced
    @Bean
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }

<dependency>
  <groupId>org.springframework.cloud</groupId>
  <artifactId>spring-cloud-loadbalancer</artifactId>
</dependency>

restTemplate.postForObject(url, 返回类型);
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容