0

I have a set of objects, each of which has an id value (int). I want to write a function which takes the object set as input, calculates a score (double) for each object, and returns a sorted array of object ids where the returned ids are stored in order of the "score" obtained.

I thought this would be easy, but I can't find a simple way of achieving this in less than 10 lines of code. (I'm using jdk 7)

Here's my code:

private ArrayList<Integer> getBlockIds(IndexKey key) {
    ArrayList<Integer> blockIds;
    Set<IndexKey> adjKeys = indexAPI.getAdjacentKeys(key, 1);
    Comparator cmp = new Comparator("Levenshtein"); 
    for ( IndexKey aKey : adjKeys ) {
        if ( cmp.similarity(key.getValue(), aKey.getValue()) >= 0.75 ) { 
            blockIds.add(aKey.getBlockId);
        }
    }
    return blockIds;
}

I want blockIds to be stored in order of score (highest first)

swami
  • 673
  • 1
  • 9
  • 18

2 Answers2

1

You only need one line actually.

Given:

Set<MyClass> set;

And methods int getId() and int getScore():

List<MyClass> sorted = set.stream().sort((a, b) -> a.getScore() - b.getScore()).map(MyClass::getId).collect(Collectors.toList());
Bohemian
  • 412,405
  • 93
  • 575
  • 722
0

Here's what I came up with, based on David's suggestion

private TreeSet<Integer> getBlockIds(IndexKey key) {
    StringDistance sd = new StringDistance("Levenshtein"); //take from config
    TreeSet<IndexKey> orderedKeys = new TreeSet<IndexKey>(new Comparator<IndexKey>() {
        @Override
        private int compare(IndexKey k1, IndexKey k2) {
            double k1Score = sd.similarity(key.getValue(), k1.getValue());
            double k2Score = sd.similarity(key.getValue(), k2.getValue());
            return k1Score.compareTo(k2Score);
        }
    });
    Set<IndexKey> adjKeys = indexAPI.getAdjacentKeys(key, 1);
    for ( IndexKey aKey : adjKeys ) {
        if ( sd.similarity(key.getValue(), aKey.getValue()) >= 0.75 ) { //take from config
            orderedKeys.add(aKey);
        }
    }
    TreeSet<Integer> blockIds;
    for ( IndexKey k : orderedKeys ) {
        blockIds.add(k.getBlockId);
    }
    return blockIds;
}
swami
  • 673
  • 1
  • 9
  • 18