Here are some of my favorite simple, yet handy routines in guava:
List<String> lines = Files.readLines(file, charset);
This is the same as FileUtils.readLines()
in apache commons io, but updated to use generics. Files
doesn’t quite have all the things that FileUtils
has, but there are many other helpful methods like deleteRecursively()
, createParentsDir()
, and move()
.
boolean isEmpty = Strings.isNullOrEmpty(yourString);
You’ve probably written something like this already, perhaps even several versions scattered in different projects. Why not just use one from an established api? You might also find emptyToNull()
or repeat()
useful while you’re looking around the Strings
class.
Preconditions.checkArgument(boolean expression);
Preconditions
provides convenient ways to test arguments and throw illegal argument exceptions when necessary. There’s also checkNotNull()
, checkState()
, etc.. If your code handles validating arguments haphazardly, preconditions can be a standard, concise way to deal with them.
Map<String, Date> sampleMap = Maps.newHashMap();
Try creating your generic collections without having to duplicate the generic types and you won’t want to go back. Joshua Bloch helped design guava’s collections package so it might as well be part of the official java collections api now.
String relativeFilePath = Joiner.on("/").join(filePieceArray);
Joiner
feels so natural to use. It’s quite handy for making file paths, comma-separated string lists, etc. without worrying about that trailing separator. Guava’s splitter also has nice advantages over String.split()
.
boolean targetIsInArray = Ints.contains(int[] array, int target)
Not earth-shattering, but again, very convenient. Ints
(and Doubles
, Floats
, etc.) also has concat()
, lastIndexOf()
, and other methods that let you deal with arrays as a whole without manually iterating through them to find what you want.
Read full article from Google’s guava java: the easy parts | Coppery Keen Claws
No comments:
Post a Comment