Filter items from a set in Java

I have a list of elements (e.g. strings) that I need to sort / filter.

The end result should not contain duplicates (easy), I will put them all in Set. So now I have a rowset.

more explanation ..

I also have an x ​​method that calculates the difference between two lines (using Levenstein distance).

Question:

Before you insert a new a String stringin my the Set set, I want to check the distance levenstein using the method xbetween stringevery other line in set, and if you xreturn >=3what I did not have to add it.

What is my best chance to do this? Except for repeating scroll setfor each stringto insert?

+5
source share
3 answers

Iterating through Setwould be your best bet as there is no built-in implementation Setto help you narrow down your possibilities.

+2
source

I played with my idea how to do it. I cannot think of a way to do this without any iteration.

Suppose you have a method with a name distance(String,String):intthat returns a given distance between two lines.

String x = "Obi-wan"; //this is the item subject to eval addition
List<String> items = new ArrayList<String>(asList("Luke","Yoda","Anakin"));
if (items.filter(s -> distance(s, x) >= 3).getFirst() == null) {
  items.add(x);
}

If you use JDK8 Preview , you can do this as soon as possible using the code above. The Iterables.getFirst () method will not iterate the entire collection, but only until the first item that matches the criteria is found.

, , Predicate .

interface Predicate<T> {
    public boolean eval(T o);
}

public static void main(String[] args) {
   final String x = "Obi-wan"; //this is the item subject to eval addition
   List<String> items = new ArrayList<String>(asList("Luke","Yoda","Anakin"));
   Predicate<String> p = new Predicate<String>() {
       public boolean eval(String s){ 
           return distance(s, x) >= 3;
       }
   };
   if(filter(items, p).isEmpty()){ 
        items.add(x);
   }
}

public static <T> List<T> filter(List<? extends T> items, Predicate<? super T> predicate){
    List<T> destiny = new ArrayList<T>();
    for(T item : items){
       if(predicate.eval(item){
           destiny.add(item);
       }
    }
    return destiny;
}

, , .

+2

. , , ( ), .

, , ​​ . ( , , )

: :

, , ( ), , .

OTOH, as soon as a line passes the test of equal peers and is inserted into the set, no other line in the set will be compared with this one, therefore the lines in the set will use their natural row order, which determines the full ordering, therefore, as part of internal operations (for example, sorting ) there are no additional inconsistencies.

+1
source

All Articles