All Downloads are FREE. Search and download functionalities are using the official Maven repository.

de.tsl2.nano.util.FuzzyFinder Maven / Gradle / Ivy

Go to download

TSL2 Framework Commons (Collections, Actions/Excecution, Readers, Xml, Print, Mail, FuzzyFinder, Proxies, Network-Structure)

There is a newer version: 2.5.2
Show newest version
/*
 * File: $HeadURL$
 * Id  : $Id$
 * 
 * created by: Tom
 * created on: 24.03.2017
 * 
 * Copyright: (c) Thomas Schneider 2017, all rights reserved
 */
package de.tsl2.nano.util;

import java.util.HashMap;
import java.util.Map;

import de.tsl2.nano.core.util.StringUtil;

/**
 * generic fuzzy finder. see {@link IFuzzyDescriptor} as descriptor for data and filter.
 * 
 * @author Tom
 * @version $Revision$
 */
public class FuzzyFinder {
    private IFuzzyDescriptor descriptor;

    /**
     * constructor
     */
    public FuzzyFinder(IFuzzyDescriptor descriptor) {
        this.descriptor = descriptor;
    }

    public FuzzyFinder(final Iterable availables) {
        descriptor = new IFuzzyDescriptor() {
            @Override
            public Iterable getAvailables() {
                return availables;
            }

            @Override
            public double distance(T item, String expression) {
                return StringUtil.fuzzyMatch(item, expression);
            }
        };
    }

    public T find(String filter) {
        Map result = fuzzyFind(filter);
        return (result.size() > 0 && result.containsKey(1d) ? result.get(1d) : null);
    }

    @SuppressWarnings("unchecked")
    public > M fuzzyFind(String filter) {
        HashMap map = new HashMap();
        Double match;
        Iterable availables = descriptor.getAvailables();
        for (T element : availables) {
            match = descriptor.distance(element, filter);
            if (match > 0) {
                while (map.containsKey(match))
                    match += 0000000001;
                map.put(match, element);
            }
        }
        return (M) map;
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy