10 Nov 2017

java 常用方法

  1. list转数组
    public static Object[] List2Array(List<Object> oList) {   
         Object[] oArray = oList.toArray(new Object[] {});   
         // TODO 需要在用到的时候另外写方法,不支持泛型的Array.   
         return oArray;   
     }
    
  2. set转数组
     public static Object[] Set2Array(Set<Object> oSet) {   
         Object[] oArray = oSet.toArray(new Object[] {});
         // Object[] oArray = oSet.toArray(new Object[0]);   
         // TODO 需要在用到的时候另外写方法,不支持泛型的Array.   
         return oArray;   
     }
    
  3. set转list
     public static <T extends Object> List<T> Set2List(Set<T> oSet) {   
         List<T> tList = new ArrayList<T>(oSet);   
         // TODO 需要在用到的时候另外写构造,根据需要生成List的对应子类。   
         return tList;   
     }
    
  4. 数组转List
    public static <T extends Object> List<T> Array2List(T[] tArray) {   
         List<T> tList = Arrays.asList(tArray);   
         // asList()返回的tList无法add(),remove(),clear()等影响集合个数操作,   
         List<T> tList = new ArrayList<T>(Arrays.asList(tArray));   
         return tList;   
     }
    
  5. List转Set
     public static <T extends Object> Set<T> List2Set(List<T> tList) {   
     Set<T> tSet = new HashSet<T>(tList);   
     //TODO 具体实现看需求转换成不同的Set的子类。   
     return tSet;   
     }
    
  6. Array转Set
     public static <T extends Object> Set<T> Array2Set(T[] tArray) {   
         Set<T> tSet = new HashSet<T>(Arrays.asList(tArray));   
         // TODO 没有一步到位的方法,根据具体的作用,选择合适的Set的子类来转换。   
         return tSet;   
     } 
    
     public static <T extends Object> Set<T> Array2Set2(T[] tArray) {   
         Set<T> tSet = new HashSet<T>();  
         Collections.addAll(tSet, tArray);    
         return tSet; 
     } 
    
  7. java实现定时任务的三种方法
    public class Task1 {  
        public static void main(String[] args) {  
       final long timeInterval = 1000;  
       Runnable runnable = new Runnable() {  
           public void run() {  
               while (true) {  
                   System.out.println("Hello !!");
                   try {  
                       Thread.sleep(timeInterval);  
                   } catch (InterruptedException e) {  
                       e.printStackTrace();  
                   }  
               }  
           }  
       };  
       Thread thread = new Thread(runnable);  
       thread.start();  
        }  
    }  
    public class Task2 {  
        public static void main(String[] args) {  
       TimerTask task = new TimerTask() {  
           @Override  
           public void run() {  
               System.out.println("Hello !!!");  
           }  
       };  
       Timer timer = new Timer();  
       long delay = 0;  
       long intevalPeriod = 1 * 1000; 
       timer.scheduleAtFixedRate(task, delay, intevalPeriod);  
        } 
    }
    public class Task3 {  
        public static void main(String[] args) {  
       Runnable runnable = new Runnable() {  
           public void run() { 
               System.out.println("Hello !!");  
           }  
       };  
       ScheduledExecutorService service = Executors  
               .newSingleThreadScheduledExecutor();  
       // 第二个参数为首次执行的延时时间,第三个参数为定时执行的间隔时间  
       service.scheduleAtFixedRate(runnable, 10, 1, TimeUnit.SECONDS);  
        }  
    } 
    //取消定时器:
    timer.cancel();
    //从当前时间立刻发起定时器
    //timer.schedule(runTimes(args), new Date(), time);// 每隔一秒输出 
    
  8. string 与 Array 互转
    // string->array
         String seperateStr = "111,222,333,444,555,666,777";
    //      String[] seperates = StringUtils.split(seperateStr, ",");
         String[] seperates = seperateStr.split(",");        
         for(String a :seperates){
             System.out.println(a);
         }       
    // array->string
         String resultStr = StringUtils.join(seperates, ",");
         //System.out.println(Arrays.toString(seperates));
         //Arrays.asList(seperates)
         //Arrays.toString(new String[0])
    
  9. JAVA中实现链式操作
    //Persion.java:
    public class Persion {
     private int id;
     private String name;   
     public  Persion() {    }
     public Persion setId(int id) { 
         this.id = id;
         return this;
     }
     public Persion setName(String name) {
         this.name = name;
         return this;
     }
     public Persion printId() {
         System.out.println(this.id);
         return this;
     }
     public Persion printName() {
         System.out.println(this.name);
         return this;
     }   
    }
    
    //Test.java:
    public class Test {
     public static void main(String[] args) {
         Persion persion1 = new Persion();
         persion1.setId(3).setName("John");
         persion1.printId().printName();
     }
    }
    
  10. Java使用占位符拼接字符串
    String stringFormat  = "error at position %s, encountered %s, expected %s ";
    System.out.println(String.format(stringFormat, 123, 100, 456));  
    String messageFormat ="error at  {0}, encountered {1}, expected {2}";
    System.out.println(MessageFormat.format(messageFormat, new Date(), 100, 456));
    String.format("%06d", 12) //000012
    
  11. 日期比较
     //   1. 第一种直接用字符串类的compareTo方法:
        String t1="20131011";
        String t2="20131030";
         int result = t1.compareTo(t2);
     //   2. 第二种是把这个日期字符串转换成long:
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        Date d1 = sdf.parse(t1);
        Date d2 = sdf.parse(t2);
        long result = d1.getTime()-d2.getTime();
     //   3. 第三种是把日期字符串转换成整形int:
        int int1 = Integer.parseInt(t1);
        int int2 = Integer.parseInt(t2);
        int result = int1-int2;
     //   注:result大于0,则t1>t2;
     //      result等于0,则t1=t2;
     //      result小于0,则t1<t2;
    
  12. 数据互通
     //同步开关
     Boolean  currentSign = true;
     int  poolSize = 10;
     ExecutorService fixedThreadPool = Executors.newFixedThreadPool(poolSize);
      if(currentSign){
            Thread t=new Thread(){
                private T param;
                private  String path;
                private Class  callback;
                private void init(T param,String path,Class  callback){
                    this.param=param;
                    this.path=path;
                    this.callback=callback;
                };
                {
                    init(param,path,callback);
                }
                public void run(){
                    //保存信息操作
                    try {
                        Client client = ClientBuilder.newClient();
                        Response response = client.target(url+path)
                                .register(JacksonFeature.class)
                                .request(MediaType.APPLICATION_JSON_TYPE)
                                .header("shd_yunzheng_api_key", "c5LjOzsxNDkwNTc5NTA5NDYy")
                                .post(Entity.entity(param, MediaType.APPLICATION_JSON_TYPE));
                                log.error("数据交互( url:{},parm:{})",(url+path),JSON.toJSONString(param));
                         response.readEntity(resMsg.class);
                    }catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            };
            t.start();
        }
    return null;
    
  13. maven 使用本地jar
    <dependency>
      <groupId>com.jun</groupId>
      <artifactId>abc</artifactId>
      <version>150</version>
      <scope>system</scope>
      <systemPath>${project.basedir}/src/main/resources/lib/abc.jar </systemPath>
    </dependency>
    
  14. 自定义error
    {
      "exception": "customized exception",
      "add-attribute": "add-attribute",
      "path": "customized path",
      "trace": "customized trace",
      "error": "customized error",
      "message": "customized message",
      "timestamp": 1498892609326,
      "status": 100
    }
    
  15. 数组排序
     Collections.sort(infos, new Comparator<YzPhotoInfo>() {
     @Override
     public int compare(YzPhotoInfo o1, YzPhotoInfo o2) {
         int compareIntroduceId= o1.getIntroduceId().compareTo(o2.getIntroduceId());
         if(compareIntroduceId==0){
           return   o1.getPhoto().getName().compareTo(o2.getPhoto().getName());
         }
         return  compareIntroduceId;
     }
     });
    

Tags: