java 用法记录
1.列表拼接成字符串
#1.1
String result = Joiner.on("_").join(list);
#1.2
String result = list.stream().collect(Collectors.joining("_"));
2.Java8的foreach()中使用return/break/continue
foreach()处理集合时不能使用break和continue这两个方法
可以试用return实现continue的功能(return不会退出循环)
举例
public static void main(String[] args) { List<String> lst = Arrays.asList("12", "3", "12345", "123"); lst.stream().forEach(e->{ if (e.length() >= 5){ return; } System.out.println(e); }); }
输出
12 3 123
3. 计算耗时
StopWatch stopWatch = new StopWatch(); stopWatch.start("testStopWatch"); stopWatch.stop(); double thickestWorkSeconds = stopWatch.getTotalTimeSeconds();
4.切割 split
List<String> mm = Arrays.asList("1243+122".split("+"));
提示报错:Dangling quantifier '+'
解:需转义:"1243+122".split("\\+")
5.Collections.singleton
返回一个Set集合,其中的元素为一个只包含object(obj)的不可变集合
6.Arrays.asList()
List<String> myList = Arrays.asList("Apple", "Orange");
Set<String> taskIdSet = new HashSet<>(Arrays.asList(taskIds.split(",")));
7.写文件
FileWriter fileWriter = new FileWriter("out.txt", false); // 2参数,false 不追加,true追加 BufferedWriter bufferWriter = new BufferedWriter(fileWriter); bufferWriter.write("content"); bufferWriter.close();