Last active
June 29, 2021 17:16
-
-
Save VenkataRaju/7674d24f9e954daa1eefa177ec1e9a9b to your computer and use it in GitHub Desktop.
Java Util
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public final class Util | |
{ | |
/** Returns unique parent paths without their child paths */ | |
public static Collection<Path> uniqueParentPaths(Collection<Path> paths) | |
{ | |
if (paths.isEmpty()) | |
return Collections.emptySet(); | |
Set<Path> parentPaths = new TreeSet<>(paths); | |
Iterator<Path> it = parentPaths.iterator(); | |
Path prev = it.next(); | |
while (it.hasNext()) | |
{ | |
Path next = it.next(); | |
if (next.startsWith(prev)) | |
it.remove(); | |
else | |
prev = next; | |
} | |
return parentPaths; | |
} | |
static void versionStringComparisonTest() | |
{ | |
List<String> list = Arrays.asList("version-10", "version-2", "version-21", "version-1", "version-10.1"); | |
Pattern p = Pattern.compile("\\d+"); | |
List<String> sortedList = list.stream() | |
.map(str -> Map.entry(str, p.matcher(str).results().map(MatchResult::group) | |
.mapToInt(Integer::parseInt) | |
.toArray())) | |
.sorted(Entry.comparingByValue(Arrays::compare)) | |
.map(Entry::getKey) | |
.collect(Collectors.toList()); | |
System.out.println(sortedList); | |
// [version-1, version-2, version-10, version-10.1, version-21 | |
} | |
static void versionStringComparisonTest2() | |
{ | |
List<String> list = Arrays.asList( | |
"S_99991.txt", | |
"S_14.txt", | |
"S_2.txt", | |
"S_7.txt", | |
"S_9990.txt", | |
"S_999.txt", | |
"S_30.txt", | |
"S_1000.txt", | |
"S_1.txt", | |
"S_02_7.txt", | |
"S_020_3.txt", | |
"S_000_7.txt", | |
"S_00000000.txt", | |
"S.txt"); | |
/* | |
* 2 -> 2 | |
* 02 -> 2 | |
* 00 -> 0 | |
*/ | |
Function<String, String> removeLeadingZerosExceptLastOne = numStr -> | |
{ | |
int i = 0; | |
for (int li = numStr.length() - 1; i < li && numStr.charAt(i) == '0'; i++); | |
return numStr.substring(i); | |
}; | |
Pattern p = Pattern.compile("\\d+"); | |
List<String> sortedList = list.stream() | |
.map(str -> Map.entry(str, p.matcher(str).results().map(MatchResult::group) | |
.map(removeLeadingZerosExceptLastOne) | |
// .toArray(String[]::new))) | |
.collect(Collectors.toList()))) | |
// .sorted(Entry.comparingByValue((numStrArr1, numStrArr2) -> Arrays.compare(numStrArr1, numStrArr2, | |
.sorted(Entry.comparingByValue((numStrArr1, numStrArr2) -> compare(numStrArr1, numStrArr2, | |
Comparator.comparingInt(String::length).thenComparing(Comparator.naturalOrder())))) | |
.map(Entry::getKey) | |
.collect(Collectors.toList()); | |
sortedList.forEach(System.out::println); | |
List<String> expectedSortedList = Arrays.asList("S.txt", | |
"S_00000000.txt", | |
"S_000_7.txt", | |
"S_1.txt", | |
"S_2.txt", | |
"S_02_7.txt", | |
"S_7.txt", | |
"S_14.txt", | |
"S_020_3.txt", | |
"S_30.txt", | |
"S_999.txt", | |
"S_1000.txt", | |
"S_9990.txt", | |
"S_99991.txt"); | |
System.out.println("\n" + sortedList.equals(expectedSortedList)); | |
/* | |
* Output: | |
* ------- | |
* S.txt | |
* S_00000000.txt | |
* S_000_7.txt | |
* S_1.txt | |
* S_2.txt | |
* S_02_7.txt | |
* S_7.txt | |
* S_14.txt | |
* S_020_3.txt | |
* S_30.txt | |
* S_999.txt | |
* S_1000.txt | |
* S_9990.txt | |
* S_99991.txt | |
* | |
* true | |
*/ | |
} | |
public static <T> int compare(Iterable<? extends T> i1, Iterable<? extends T> i2, Comparator<? super T> cmp) | |
{ | |
Objects.requireNonNull(cmp); | |
if (i1 == i2) | |
return 0; | |
if (i1 == null || i2 == null) | |
return i1 == null ? -1 : 1; | |
Iterator<? extends T> i2It = i2.iterator(); | |
for (T aEl : i1) | |
{ | |
if (!i2It.hasNext()) | |
return 1; | |
T bEl = i2It.next(); | |
int v = cmp.compare(aEl, bEl); | |
if (v != 0) | |
return v; | |
} | |
return i2It.hasNext() ? -1 : 0; | |
} | |
static List<String> extractPositiveNumbers(String str) | |
{ | |
var nums = new ArrayList<String>(); | |
var sb = new StringBuilder(); | |
var hasLeadingZeros = false; | |
for (int i = 0, cp; i < str.length();) | |
{ | |
cp = str.codePointAt(i); | |
var isDigit = true; | |
if (cp >= '1' && cp <= '9') | |
sb.append((char) cp); | |
else if (cp == '0') | |
{ | |
if (sb.length() == 0) | |
hasLeadingZeros = true; | |
else | |
sb.append((char) cp); | |
} | |
else | |
isDigit = false; | |
i += Character.charCount(cp); | |
if (!isDigit || i == str.length()) | |
{ | |
if (sb.length() != 0) | |
{ | |
nums.add(sb.toString()); | |
sb.setLength(0); | |
} | |
else if (hasLeadingZeros) | |
{ | |
nums.add("0"); | |
} | |
hasLeadingZeros = false; | |
} | |
} | |
return nums; | |
} | |
public static List<String> split(String str, char sepChar, char escChar) | |
{ | |
if (sepChar == escChar) | |
throw new IllegalArgumentException("sepChar[" + sepChar + "] and escChar should not be same"); | |
List<String> parts = new ArrayList<>(); | |
StringBuilder part = new StringBuilder(); | |
for (int i = 0, len = str.length(); i < len; i++) | |
{ | |
char c = str.charAt(i); | |
if (c == sepChar) | |
{ | |
parts.add(part.toString()); | |
part.setLength(0); | |
continue; | |
} | |
if (c == escChar) | |
{ | |
char nc; | |
if ((i + 1) < len && ((nc = str.charAt(i + 1)) == sepChar || nc == escChar)) | |
{ | |
part.append(nc); | |
i++; | |
continue; | |
} | |
// Strict implementation should throw exception here as escChar is not escaped properly | |
} | |
part.append(c); | |
} | |
parts.add(part.toString()); | |
return parts; | |
} | |
public static <T> void sort(List<T> listToBeOrdered, List<? extends T> referenceOrderedList) | |
{ | |
sort(listToBeOrdered, Function.identity(), referenceOrderedList, Function.identity()); | |
} | |
public static <A, B, P> void sort(List<A> listToBeOrdered, Function<A, P> aPropertyExtractor, | |
Collection<? extends B> referenceOrderedCollection, Function<B, P> bPropertyExtractor) | |
{ | |
listToBeOrdered.sort(comparator(aPropertyExtractor, referenceOrderedCollection, bPropertyExtractor)); | |
} | |
public static <A, B, P> Comparator<A> comparator(Function<A, P> aPropertyExtractor, | |
Collection<? extends B> referenceOrderedCollection, Function<B, P> bPropertyExtractor) | |
{ | |
Map<P, Integer> priorityByProperty = new HashMap<>(); | |
for (B b : referenceOrderedCollection) | |
priorityByProperty.put(bPropertyExtractor.apply(b), priorityByProperty.size()); | |
return Comparator.comparing(aPropertyExtractor, | |
Comparator.comparing(priorityByProperty::get, Comparator.nullsLast(Comparator.naturalOrder()))); | |
} | |
static IntStream intStream(IntSupplier intSupplier) | |
{ // Impl: See CharSequence#codePoints | |
var intIterator = new PrimitiveIterator.OfInt() | |
{ | |
@Override | |
public boolean hasNext() | |
{ | |
return true; | |
} | |
@Override | |
public int nextInt() | |
{ | |
return intSupplier.getAsInt(); | |
} | |
}; | |
var intSpliterator = Spliterators.spliteratorUnknownSize(intIterator, Spliterator.ORDERED); | |
return StreamSupport.intStream(intSpliterator, Spliterator.ORDERED, false); | |
} | |
/** | |
* Strips character '' (Zero Width Non Breaking Space) from the String, in addition to the | |
* white space characters covered by {@link String#strip()} method | |
*/ | |
public static String moreStrip(String str) | |
{ | |
int charToTrim = ''; | |
while (true) | |
{ | |
str = str.strip(); | |
int start = 0, end = str.length(), cp; | |
for (; (start < end) && ((cp = str.codePointAt(start)) == charToTrim); start += Character.charCount(cp)); | |
for (; (end > 0) && ((cp = str.codePointBefore(end)) == charToTrim); end -= Character.charCount(cp)); | |
if (start == 0 && end == str.length()) | |
break; | |
str = str.substring(start, end); | |
} | |
return str; | |
} | |
public static long sizeOf(Path path) throws IOException | |
{ | |
var attrs = Files.readAttributes(path, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS); | |
if (attrs.isRegularFile()) | |
return attrs.size(); | |
if (!attrs.isDirectory()) | |
return 0; | |
try (var ds = Files.newDirectoryStream(path)) | |
{ | |
long size = 0; | |
for (Path child : ds) | |
size += sizeOf(child); | |
return size; | |
} | |
} | |
public static long sizeOf1(Path path) throws IOException | |
{ | |
var fv = new SimpleFileVisitor<Path>() | |
{ | |
long size = 0; | |
@Override | |
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException | |
{ | |
if (attrs.isRegularFile()) | |
size += attrs.size(); | |
return FileVisitResult.CONTINUE; | |
} | |
}; | |
Files.walkFileTree(path, fv); | |
return fv.size; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment