Java常用代码段

Posted by Coderidea on June 29, 2020

一 ArrayList<T> 转成 T[] 

List<String> stockList = new ArrayList<String>();
stockList.add("stock1");
stockList.add("stock2");

String[] stockArr = new String[stockList.size()];
stockArr = stockList.toArray(stockArr);

二 List 按 类的属性排序

Collections.sort(Database.arrayList, new Comparator<MyObject>() {
    @Override
    public int compare(MyObject o1, MyObject o2) {
        return o1.getStartDate().compareTo(o2.getStartDate());
    }
});

  Java8 及以上的版本  lambda  表达式

Collections.sort(Database.arrayList, 
                        (o1, o2) -> o1.getStartDate().compareTo(o2.getStartDate()));

三 Convert InputStream to byte array in Java (ImputStream 转 byte[])

   使用 Apache Commons IO

InputStream is;
byte[] bytes = IOUtils.toByteArray(is);

  或者  google guava 

byte[] bytes = ByteStreams.toByteArray(inputStream);

四 convert an InputStream into a String in Java(inputStream 转成 string)

使用 Apache Commons IO

StringWriter writer = new StringWriter();
IOUtils.copy(inputStream, writer, encoding);
String theString = writer.toString();

or 

// NB: does not close inputStream, you'll have to use try-with-resources for that
String theString = IOUtils.toString(inputStream, encoding); 

Using CharStreams (Guava)

String result = CharStreams.toString(new InputStreamReader(
      inputStream, Charsets.UTF_8));

五 Maven project 引入本地jar包

 
<dependency>
    <groupId>com.sample</groupId>
    <artifactId>sample</artifactId>
    <version>1.0</version>
    <scope>system</scope>
    <systemPath>${project.basedir}/src/main/resources/yourJar.jar</systemPath>
</dependency>