Python rstrip in Java

by GarciaPL on Friday 13 July 2018

Last time I was working on migration of some code from Python into Java and I was trying to find a corresponding code in Java for a function called rstrip in Python. So, below you can see a code written in Python and solution written in Java produced of course using Guava.

icb_code.rstrip("0")


CharMatcher trailingZeroMatcher = CharMatcher.is('0');
String trimmedInput = trailingZeroMatcher.trimTrailingFrom(input);

Case Insensitive Map in Java

by GarciaPL on Wednesday 11 July 2018

I needed recently to create a case-insensitive map in Java to query it with keys which might be uppercase or lowercase. I thought that it should be somewhere some kind of solution already available for developers. I found a class called CaseInsensitiveMap in Apache Commons Collections package (https://commons.apache.org/proper/commons-collections/apidocs/org/apache/commons/collections4/map/CaseInsensitiveMap.html) but unfortunately, I found later on that it does not support generics which was needed in my case, that's why I decided to go with a custom solution for that problem which might be found below.

Map<String, String> record = getRecord();

TreeMap<String, String> caseInsensitiveMap = new TreeMap<>getCaseInsensitiveComparator());

caseInsensitiveMap.putAll(record);

protected Comparator<String> getCaseInsensitiveComparator() {
    return Comparator.nullsFirst(String.CASE_INSENSITIVE_ORDER);
}

Splitting list by enum property to get map of enum and list

by GarciaPL on Sunday 1 July 2018

Last time I had a problem with how to split the incoming list of a type File, to get a map of list of files by FileType, which is a property of File class. The easiest way to achieve it? Reduce.

Input -> List<File> listOfFiles
Output -> Map<FileType, List<File>>

public Map<FileType, List<File>> splitFilesByFileType(List<File> listOfFiles) {
    return listOfFiles.stream()
        .reduce(new HashMap<>(), (filesByFileType, file) -> {
            FileType fileType = file.getFileType();
            if (filesByFileType.containsKey(fileType)) {
                filesByFileType.get(fileType).add(file);
            }
            else {
                filesByFileType.putIfAbsent(fileType, Lists.newArrayList(file));
            }

            return filesByFileType;
        }, (acc1, acc2) ->
        {
            acc1.putAll(acc2);
            return acc1;
        });
}