本文主要是介绍Java常用代码段,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
一 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>() {@Overridepublic 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>
这篇关于Java常用代码段的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!