Compare two string sequences (files, resource streams, anything that can be expressed as sequence of lines). Possibly ignore line endings, possible ignore leading and/or trailing whitespace, possibly ignore case. Useful for testing when you have an expected file as a resource, say, and need to co
| 39 | * need to compare it to output of some execution. |
| 40 | */ |
| 41 | public class StringsCompare { |
| 42 | /** |
| 43 | * A source of lines. Essentially, an iterator with IOExceptions. Also |
| 44 | * supports the use of predicates to skip lines testing true. |
| 45 | */ |
| 46 | interface LineSource extends Closeable { |
| 47 | /** |
| 48 | * Has a line? |
| 49 | * @return ture if another line exists. |
| 50 | * @throws IOException on error |
| 51 | */ |
| 52 | boolean hasLine() throws IOException; |
| 53 | |
| 54 | /** |
| 55 | * Fetch next line. |
| 56 | * @return next line |
| 57 | * @throws IOException on error |
| 58 | */ |
| 59 | String nextLine() throws IOException; |
| 60 | |
| 61 | @Override |
| 62 | default void close() throws IOException { |
| 63 | |
| 64 | } |
| 65 | } |
| 66 | |
| 67 | /** |
| 68 | * Predicate to skip no lines. |
| 69 | */ |
| 70 | public static Predicate<String> SKIP_NONE = (s) -> false; |
| 71 | |
| 72 | /** |
| 73 | * Predicate to skip whitespace only lines. |
| 74 | */ |
| 75 | public static Predicate<String> SKIP_BLANK = (s) -> s.trim().length() == 0; |
| 76 | |
| 77 | /** |
| 78 | * Predicate to skip empty lines. |
| 79 | */ |
| 80 | public static Predicate<String> SKIP_EMPTY = (s) -> s.length() == 0; |
| 81 | |
| 82 | /** |
| 83 | * Ident transform, use when you want no mapping done on strings. |
| 84 | */ |
| 85 | public static final Function<String, String> IDENT = (s) -> s; |
| 86 | |
| 87 | /** |
| 88 | * Mapping transform to remove leading whitespace. |
| 89 | */ |
| 90 | public static final Function<String, String> TRIM_LEADING_WHITESPACE = (s) -> { |
| 91 | int i = 0; |
| 92 | for (; i < s.length(); i++) { |
| 93 | if (!Character.isWhitespace(s.charAt(i))) { |
| 94 | break; |
| 95 | } |
| 96 | } |
| 97 | if (i > 0) { |
| 98 | return s.substring(i); |