JAV所有开发公共代码

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JAV所有开发公共代码相关的知识,希望对你有一定的参考价值。

======================================================================================================

公共的方法
----------------------------------------------------------------------
> 遍历list 移除当前的某个
private void removeNoRelProd(List<EventMergeDto> data) {
    if (data != null) {
        for (Iterator<EventMergeDto> it = data.iterator(); it.hasNext(); ) {
            EventMergeDto dto = it.next();
            if (dto.getProds() == null || dto.getProds().isEmpty()) {
                it.remove();
            }
        }
    }
}

----------------------------------------------------------------------
> sql in  拼写
// import org.apache.commons.lang.StringUtils;
public static void main(String[] args) {
    List<String> conceptIds = Arrays.asList("1212,69437hfuit,32ui,iu3i".split(","));
    System.out.println(String.join(",", conceptIds));// 1212,69437hfuit,32ui,iu3i
    // 或 StringUtils.join(conceptIds,",")
    
    List<String> sids = Arrays.asList("1212,69437hfuit,32ui,iu3i".split(","));
    String sql  = "select * from nlp_en where textid in" + "(‘"+StringUtils.join(sids,"‘,‘")+"‘)";
    System.out.println(sql);//  select * from nlp_en where textid in(‘1212‘,‘69437hfuit‘,‘32ui‘,‘iu3i‘)
}
----------------------------------------------------------------------
>List转map
List<News> newsLists = newsDao.findAll(newsids);
Map<String,News> newMaps = newsLists.stream().map((one)->{return one;}).collect(Collectors.toMap(k->k.get_id().toString(), v->v));
或
Map<String,News> newMaps = newsLists.stream().collect(Collectors.toMap(k->k.get_id().toString(), v->v));
或
Map<String,News> newMaps = newsLists.stream().map(one->one).collect(Collectors.toMap(k->k.get_id().toString(), v->v));

> toList
List<EventList> newMaps = newsLists.stream().map(one->one).collect(Collectors.toList());

> toSet
Set<String> newMaps = newsLists.stream().map(one->one).collect(Collectors.toSet());

----------------------------------------------------------------------
>List 去重
//方式一
List<String> list = Arrays.asList("admin,test,passwd,passwd,test".split(","));
System.out.println(list);
list =  list.stream().distinct().collect(Collectors.toList());
System.out.println(list);

//方式二
List<News> news = newsDao.findNewsByComsOrInds(query,offset,limit);
// 根据title去重
Set<News> newSet = new TreeSet<>((o1, o2) -> o1.getTitle().compareTo(o2.getTitle()));
newSet.addAll(news);
news = new ArrayList<>(newSet);

//方式三
List<News> disNews = Lists.newArrayList();
news.forEach((one)->{
    String title = one.getTitle().trim();
    if(!set.contains(title)){
        set.add(title);
        disNews.add(one);
    }
});
news = disNews;

----------------------------------------------------------------------

/**
     * import java.time.LocalTime;
     * import java.time.format.DateTimeFormatter;
     */
    public static void main(String[] args) throws ParseException {
        DateTimeFormatter CLNHHMM = DateTimeFormatter.ofPattern("HH:mm");
        LocalTime time = LocalTime.parse("16:25", CLNHHMM);
        System.out.println(time);

        System.out.println(Optional.ofNullable(time)); // 16:25

        List<String> crons = new ArrayList<>();
        // time不为空的话,放入   java.util.Optional;
        Optional.ofNullable(time).ifPresent(t -> {
            crons.add(String.format("0 %d %d * * ?", t.getHour(), t.getMinute()));
        });

        System.out.println(crons);



        LocalDateTime ldt_current= LocalDateTime.now();
        System.out.println(ldt_current); // 2017-11-27T11:27:51.702
         
        LocalDateTime ldt_before = ldt_current.plusHours(-24);
        System.out.println(ldt_before); //  2017-11-26T11:27:51.702
         
        String curr_format = ldt_current.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS"));
        String before_format = ldt_before.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS"));        
        System.out.println(curr_format);  // 2017-11-27 11:27:51.702
        System.out.println(before_format); // 2017-11-26 11:27:51.702
    }


>时间
import java.time.LocalDate; // jdk

LocalDate today = LocalDate.now();  // 2017-10-25
LocalDate tomorrow = today.plusDays(1); // 2017-10-26
String st = String.join(" ",today.toString(),"00:00:00"); // 2017-10-25 00:00:00
String et=String.join(" ",tomorrow.toString(),"00:00:00"); // 2017-10-26 00:00:00

----------------------------------------------------------------------
> 当前时间往前退一个月的时间

Date trdt = new Date();
String startDt = DateUtil.formatDate(DateUtils.addMonths(trdt, -1), "yyyyMMdd");

----------------------------------------------------------------------
>BigDecimal 保留小数位数 四舍五入

/**
 * 保留小数位数  四舍五入
 * @param val 值    scale 保留几位
 */
public static Double scale(Double val, int scale){
    if(val == null || val.isInfinite() || val.isNaN()) {
        return 0d;
    }
    BigDecimal bg = new BigDecimal(val);
    //进行四舍五入 然后保留多少位
    return bg.setScale(scale, BigDecimal.ROUND_HALF_UP).doubleValue();
}
----------------------------------------------------------------------
> bigDecimal 相加
BigDecimal g = new BigDecimal(1.236d);
g = g.add(new BigDecimal(0.5d));
g = g.add(new BigDecimal(0.5d));
System.out.println(g.doubleValue());    
----------------------------------------------------------------------
>利用正则表达式校验

private static boolean filterSecu(String cd) {
    String regex = "^(6.*SH_EQ)|((0|3).*SZ_EQ)$";
    Pattern pattern = Pattern.compile(regex);
    Matcher matcher = pattern.matcher(cd);
    boolean find = matcher.find();
    return find;
}

String time = "20160406150519";
Pattern    pattern = Pattern.compile("^[0-9]{8}15[0-9]{4}");
if(pattern.matcher(time).matches()) {
    return time.substring(0, 8) + "150000";
    System.out.println("当前匹配");
}else{
    System.out.println("当前不匹配");
}

//验证是否为空
StringUtils.isNotBlank("");
----------------------------------------------------------------------
>判断集合是否为空

import org.apache.commons.collections.CollectionUtils;
List<S> datas = 。。。。。。;
if(CollectionUtils.isEmpty(datas)) {
        continue;
}
//判断集合不为空
if(CollectionUtils.isNotEmpty(updateEntities)) {
        updateData(updateEntities);
        entities = removeAll(entities, updateEntities);
}
----------------------------------------------------------------------
> 将逗号分隔的String 装换成list
private List<String> asList(String keys){
    List<String> list = null;
    if(StringUtils.isBland(keys)){
        list = Arrays.asList(keys.split(","));
    }
}
----------------------------------------------------------------------
>清除Map中的数据

public static Map<String, Integer> syncHqIndex = new HashMap<String, Integer>();    
syncHqIndex.remove("");

>清除List中的数据
public static List<String> clearSecus = new ArrayList<String>();
clearSecus.clear();
----------------------------------------------------------------------
数组实现
Arrays.asList("1001","1002","1003","1008","1005","1054","1055","1012")
List<String> dataTypeFi = Arrays.asList("11", "21", "31");

import com.google.common.collect.Lists;
Lists.newArrayList("1001,1002,1003,1012".split(","))
----------------------------------------------------------------------
private String getKey(String... args) {
        StringBuilder sb = new StringBuilder();
        for (String s : args) {
            sb.append(s);
        }
        return sb.toString();
    }
----------------------------------------------------------------------

>校验集合是否为空
import org.apache.commons.collections.CollectionUtils;

BasicDBList orList = new BasicDBList();
CollectionUtils.isEmpty(orList)
----------------------------------------------------------------------
>校验数数据是否为空

import org.apache.commons.lang3.StringUtils;
StringUtils.isBlank("")
校验数据不为空
StringUtils.isNotBlank("");       

String[] arr = str.split(splitor);
List<String> list = new ArrayList<String>(arr.length);
for(String s : arr){
    if(StringUtils.isNotEmpty(s)){
        list.add(s);
    }
}

----------------------------------------------------------------------
>switch  case 用法    
    
 // 根据股票类型取相应记录
public Set<String> getSecusByMarketType(int secuType) {
    Set<String> secus = null;
    switch (secuType) {
    case Constants.SECU_A:
        secus = baseProfileBiz.getSecusByMarket(BaseConstants.MARKET_A, null, null);
        break;
    case Constants.SECU_ABROAD:
        secus = baseProfileBiz.getSecusByMarket("H,US", null, null);
        break;
    default:
        break;
    }
    return secus;
}        

----------------------------------------------------------------------
>拼接字符串
StringUtils.join(strings, separator);
----------------------------------------------------------------------
验证数据
 public static boolean isAEquity(String code) {
        if (StringUtils.isBlank(code)) return false;
        boolean flag = false;
        Pattern p = Pattern.compile("^(6.*SH_EQ|(0|3).*SZ_EQ)$");
        Matcher m = p.matcher(code);
        if (m.matches())
            flag = true;
        return flag;
    }
----------------------------------------------------------------------

>使用System.arraycopy()实现数组之间的复制  

System提供了一个静态方法arraycopy(),我们可以使用它来实现数组之间的复制。其函数原型是:
public static void arraycopy(Object src, int srcPos, Object dest, int destPos, int length) 
src:源数组; srcPos:源数组要复制的起始位置; dest:目的数组; destPos:目的数组放置的起始位
置; length:复制的长度。 注意:src and dest都必须是同类型或者可以进行转换类型的数组. 有趣
的是这个函数可以实现自己到自己复制,比如: int[] fun ={0,1,2,3,4,5,6}; 
System.arraycopy(fun,0,fun,3,3); 则结果为:{0,1,2,0,1,2,6}; 实现过程是这样的,先生成一个长
度为length的临时数组,将fun数组中srcPos 到srcPos+length-1之间的数据拷贝到临时数组中,再执行
System.arraycopy(临时数组,0,fun,3,3)
如:
// remove one item from array
private static String[] removeItemFromArray(String[] array, int index) {
    int length = array.length;
    Object result = Array.newInstance(array.getClass().getComponentType(), length - 1);
    System.arraycopy(array, 0, result, 0, index);
    if (index < length - 1) {
        System.arraycopy(array, index + 1, result, index, length - index - 1);
    }
    return (String[]) result;
}
----------------------------------------------------------------------
//验证
import org.springframework.util.Assert;
Assert.notNull(rse, "ResultSetExtractor must not be null");
----------------------------------------------------------------------
Map<String ,Object> map = new HashMap<String,Object>();
Collection c = map.values();

----------------------------------------------------------------------
>Map遍历

Map<String, DBObject> secuInfoMap = new HashMap<String, DBObject>();
// 遍历 secuIdMap, 用orgId 作为中介, 从 orgInfoMap 中取机构名称等
for (Map.Entry<String, String> entry : secuOrgIdMap.entrySet()) {
    String secu = entry.getKey();
    String orgId = entry.getValue();

    secuInfoMap.put(secu, orgInfoMap.get(orgId));
}

private static BasicDBObject prepareDBObject(LinkedHashMap<String, Object> map) {
        BasicDBObject dbObj = new BasicDBObject();

        Set<String> s = map.keySet();
        for (String key : s) {
            dbObj.put(key, map.get(key));
        }

        return dbObj;
    }
----------------------------------------------------------------------
> map 分组

public static void main(String[] args) {
        List<EventNewsCon> list = Lists.newArrayList();
        list.add(new EventNewsCon("1", "698", new Date(),new Date()));
        list.add(new EventNewsCon("1", "25478", new Date(),new Date()));
        list.add(new EventNewsCon("1", "25478", new Date(),new Date()));
        list.add(new EventNewsCon("21", "698", new Date(),new Date()));
        list.add(new EventNewsCon("21", "12014", new Date(),new Date()));
        
        // 分组  方式一
        Map<String, List<EventNewsCon>> collect0 = Maps.newConcurrentMap();
        list.forEach((one)->{
            List<EventNewsCon> va = collect0.get(one.getEvent_id());
            if(CollectionUtils.isEmpty(va)){
                va = Lists.newArrayList();
                collect0.put(one.getEvent_id(), va);
            }
            va.add(one);
        });
        System.out.println(collect0);
        
        // 分组 方式二
        Map<String, List<EventNewsCon>> collect = list.stream().collect(Collectors.groupingBy(k->k.getEvent_id()));
        System.out.println(collect);
        
        // 分组 方式三
        Map<String, List<EventNewsCon>> collect1 = list.stream()
                .collect(Collectors.groupingBy(k->k.getEvent_id(),Collectors.mapping(v->v,Collectors.toList())));
        System.out.println(collect1);
        
        // 分组  {1=[698, 25478, 25478], 21=[698, 12014]}
        Map<String, List<String>> collect2 = list.stream()
                .collect(Collectors.groupingBy(k->k.getEvent_id(),Collectors.mapping(v->v.getNews_id(),Collectors.toList())));
        System.out.println(collect2);
        
        // 分组 value进行去重  {1=[698, 25478], 21=[698, 12014]}
        Map<String, Set<String>> collect3 = list.stream()
                .collect(Collectors.groupingBy(k->k.getEvent_id(),Collectors.mapping(v->v.getNews_id(),Collectors.toSet())));
        System.out.println(collect3);
}


----------------------------------------------------------------------
>list遍历
@SuppressWarnings("unchecked")
    private static List<String> delDuplicated(List<String> oldList) {
        Set<Object> set = new HashSet<Object>();
        List<String> newList = new ArrayList<String>();
        for (Iterator iter = oldList.iterator(); iter.hasNext();) {
            Object element = iter.next();
            if (set.add(element)) newList.add((String) element);
        }
        return newList;
    }

Map<K, V> map = ;
List<Map.Entry<K, V>> entrys = new ArrayList<>(map.entrySet());
Map<K, V> result = Maps.newLinkedHashMap();
entrys.stream().forEach((entry) -> result.put(entry.getKey(), entry.getValue()));

----------------------------------------------------------------------    
>利用StringUtils.join()方法拼接字符串
import org.apache.commons.lang.StringUtils;

List<String> results = new ArrayList<String>();
results.add(buildResultString("secu", "rpt", "item_cd", "current period", "current value", "unit",
   "previous period", "previous value", "unit", "ratio"));
   
 public static String buildResultString(String... fields){
    return StringUtils.join(fields, ",");
}
      
----------------------------------------------------------------------
> 字符串时间比较大小

String dt = "";
String oneDt = "";
if(oneDt.compareTo(dt)<0){
    System.out.println("说明oneDt < dt");
}
----------------------------------------------------------------------
> map 初始化

/**
 *  HashMap 是没有顺序的;LinkedHashMap 是有顺序的
 */
public static final Map<String, String> MARKETMAP = new HashMap<String, String>() {
    private static final long serialVersionUID = -1454726433772295097L;
    {
        put("新加坡证券交易所第一股东", "新加坡证券交易所");
        put("深圳证券交易所主板A股", "深交所主板");
        put("纳斯达克证券交易所全球精选市场", "美国NASDAQ证券交易所");
        put("上海证券交易所A股", "上交所");
        put("深圳证券交易所中小企业板", "深交所中小板");
    }
};

public static void main(String[] args) {        
    for(String s : MARKETMAP.keySet()){
        System.out.println(s+"="+MARKETMAP.get(s));
    }
    
    System.out.println("*******************************************************");
    Map<String, String> map = new LinkedHashMap<String, String>();
    map.put("新加坡证券交易所第一股东", "新加坡证券交易所");
    map.put("深圳证券交易所主板A股", "深交所主板");
    map.put("纳斯达克证券交易所全球精选市场", "美国NASDAQ证券交易所");
    map.put("上海证券交易所A股", "上交所");
    map.put("深圳证券交易所中小企业板", "深交所中小板");
    
    for(String s : map.keySet()){
        System.out.println(s+"="+map.get(s)+"  ");
    }
}
----------------------------------------------------------------------
> List 进行截取多少个

public static void main(String[] args) {
    // 方式一
    List<Object> list = new ArrayList<Object>();
    list.add("a");list.add("b");list.add("c");
    list.add("d");list.add("e");list.add("f");
    list.add("g");list.add("h");
    // [a, b, c] [d, e] [f, g]  list 的subList默认有一个规则,接取是 包含头,不包含尾部, 最有要加上最后的
    System.out.println(list.subList(0, 3) + " "+ list.subList(3, 5) + " " + list.subList(5, list.size()-1));
    String idx50Code = list.subList(0, 3).toString();
    System.out.println(idx50Code);
    System.out.println(idx50Code.substring(1,idx50Code.length()-1));
    
    // 方式二
    List<EventTimelineDto> result = new ArrayList<EventTimelineDto>();
    int offset = 25;
    int limit = 20;
    result.subList(offset, Math.min(offset+=limit, result.size()))
    
    
    // 方式三
    List<String> list = Arrays.asList("1,2".split(","));
    System.out.println(list);
    list = list.stream().limit(3).collect(Collectors.toList());
    System.out.println(list);

    list = list.stream.skip(3)limit(6).collect(Collectors.toList());
    
}
----------------------------------------------------------------------
> 数据拼接
String header = String.format("%s,%s,%s,%s,%s,%s", 
    new Object[]{"时间","tick","主力流入","主力流出","小单流入","小单流出"});
System.out.println(header);
//输出结果为 :  时间,tick,主力流入,主力流出,小单流入,小单流出

String.format("0 %d %d * * ?", "16", "25")
//输出结果为: 0 16 25 * * ?

 

以上是关于JAV所有开发公共代码的主要内容,如果未能解决你的问题,请参考以下文章

微信小程序代码片段

前端开发常用js代码片段

C#-WebForm-★内置对象简介★Request-获取请求对象Response相应请求对象Session全局变量(私有)Cookie全局变量(私有)Application全局公共变量Vi(代码片段

前端开发中最常用的JS代码片段

片段事务中的实例化错误

片段 null 必须是公共静态类才能从实例状态正确重新创建