Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7610587
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 31, 20262026-05-31T01:27:14+00:00 2026-05-31T01:27:14+00:00

Assume you read data items and associated scores from a stream source (i.e. no

  • 0

Assume you read data items and associated scores from a “stream” source (i.e. no random access or multiple passes possible).

What is the best way of keeping, at any time, only those elements in memory with lowest weight encountered so far. I would be interested in the “Java” way of doing it, the shorter the idiom the better, rather than algorithm (“use search-tree, insert new element, delete biggest if size exceeded”).

Below is the solution I came up with, however I find it a bit lengthy, also some behaviour might be unexpected (the same item with different scores is possibly kept multiple times, while the same item added with the same score is kept only once). I also feel there should be something existing for this.

import java.util.AbstractMap.SimpleEntry;
import java.util.Map.Entry;
import java.util.Comparator;
import java.util.TreeSet;

/**
 * Stores the n smallest (by score) elements only.
 */
public class TopN<T extends Comparable<T>> {
  private TreeSet<Entry<T, Double>> elements;
  private int n;

  public TopN(int n) {
    this.n = n;
    this.elements = new TreeSet<Entry<T, Double>>(
        new Comparator<Entry<T, Double>>() {
          @Override
          public int compare(Entry<T, Double> o1, Entry<T, Double> o2) {
            if (o1.getValue() > o2.getValue()) return 1;
            if (o1.getValue() < o2.getValue()) return -1;
            return o1.getKey() == null ? 1 : o1.getKey().compareTo(o2.getKey());
          }
    });
  }

  /**
   * Adds the element if the score is lower than the n-th smallest score.
   */
  public void add(T element, double score) {
    Entry<T, Double> keyVal = new SimpleEntry<T, Double>(element,score);
    elements.add(keyVal);
    if (elements.size() > n) {
      elements.pollLast();
    }
  }

  /**
   * Returns the elements with n smallest scores.
   */
  public TreeSet<Entry<T, Double>> get() {
    return elements;
  }
}

There is a similar question, but it doesn’t include the stream source / memory requirement:
Find top N elements in an Array

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-31T01:27:15+00:00Added an answer on May 31, 2026 at 1:27 am

    Use a “heap” datastructure. Java has a built in one: PriorityQueue. Simply define your comparator for “best”, and feed all your data from the stream into the priority queue.

    EDIT:

    To add a bit more colour to this answer, you probably need to do something like this:

    • Define a comparator that works the opposite way to what you want (i.e. favours the items you want to throw away) – or define one that works the right way, and wrap it with Collections.reverseOrder(...)
    • Iterate over your data and put each element into the pqueue.
    • With each insert, if the size of the pqueue is >n, use poll() to remove the “top” element from the heap – which, because of your comparator, will actually be the “worst” one.

    What you’re left with is a pqueue with n elements in which were the “least bad”.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Assume I have copied a byte buffer into a memory stream using this memoryStream.Read(data,
I want to do following: Make Oracle stored procedure for read all data from
I use xlrd to read data from excel files. For integers stored in the
I need to read data row from SQL Server 2008. The type of one
I'm designing a tool using Java 6, that will read data from Medical Devices.
So I'm making this android application, that needs to read data from user-provided CSV
All articles I've read about localization of a WinForms application assume that I already
I want to read and process sets of input from a file and then
I'd like to read some data which itself specifies the data type to use.
I need to get data from an Excel file to print them in a

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.