Java常用操作总结

Java常用操作总结,便于查询(时常更新)

将多个list合并成一个list

假设有一个列表,其中的元素还是列表,将其中的列表合并成一个大的列表:

1
2
3
List<List<Integer>> list = ...
//list2是一个合并了list中所有列表的大列表
List<Integer> list2 = list.stream().flatMap(Collection::stream).collect(Collectors.toList());

将Stream转成Array

1
2
Stream<String> stringStream = ...;
String[] stringArray = streamString.toArray(String[]::new);

将String转成InputStream

  1. 不使用第三方库
1
2
String initialString = "text";
InputStream targetStream = new ByteArrayInputStream(initialString.getBytes());
  1. 使用Guava
1
2
String initialString = "text";
InputStream targetStream = new ReaderInputStream(CharSource.wrap(initialString).openStream());
  1. 使用Commons IO
1
2
String initialString = "text";
InputStream targetStream = IOUtils.toInputStream(initialString);

按行读文件内容

1
Files.readAllLines()

stream代替fori

1
IntStream.range(1, 4)

stream sorted()

1
2
3
4
5
6
stream.sorted(Comparator.naturalOrder())
stream.sorted(Comparator.reverseOrder())
stream.sorted(Comparator.comparingDouble())
stream.sorted(Comparator.comparingLong())
stream.sorted(Comparator.comparingInt())
stream.sorted((f1, f2) -> Long.compare(f1, f2));

list to map

1
books.stream().collect(Collectors.toMap(Book::getIsbn, Book::getName));

List 转换成 double[]

1
2
List<Double> list;
list.stream().mapToDouble(Double::doubleValue).toArray()

double[] 转换成 List

1
2
double[] array;
DoubleStream.of(array).boxed().collect(Collectors.toList());

InputStream转byte[]

  1. 不使用第三方库
1
2
3
4
5
6
7
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int nRead;
while ((nRead = inputStream.read(buffer)) != -1) {
byteArrayOutputStream.write(buffer, 0, nRead);
}
byte[] bytes1 = byteArrayOutputStream.toByteArray();
  1. 使用Commons IO
1
byte[] bytes2 = IOUtils.toByteArray(inputStream);
  1. 使用Spring
1
byte[] bytes3 = StreamUtils.copyToByteArray(inputStream);
  1. 使用guava
1
byte[] bytes4 = ByteStreams.toByteArray(inputStream);