How to extract K smallest elements from a list of objects?

I scroll through the list to find a specific record, and then assign it to a variable and try to delete it later. This is easier to demonstrate than to explain.

ArrayList<Example> list1 = populate(); Example ex1 = list1.get(0); Example ex2 = ex1; list1.remove(ex2); 

I know this probably has something to do with Java's inability to handle pointers, but a viable solution would be great.

Edit: To clarify, this is a brief example of my code, and not providing you with complete information. What I do is iterate over the list to find the lowest 10 numbers. My technique is to go through the list, find the lowest one and add it to another list, then remove that number from the original list and repeat. But my list consists of objects that have an int value inside them, not a list of integers.

 for(0 to 9){ for(0 to list.size){ if(list.get(x) < smallest) smallest = list.get(x) } smallestList.add(smallest); list.remove(smallest) } 
+6
source share
3 answers

I would sort the list. Then I will create a list with these 10 smallest objects and list1 original list1 to contain the rest of the objects. Sort of:

 Collection.sort(list1); ArrayList<Example> yourSmallestElements = (ArrayList<Example>)(list1.sublist(0, 9).clone()); list1.removeAll(yourSmallestElements); 

NOTE. I cloned subscriptions because sublist() only returns a view of list1 , and that is not what you want here.

Your Example class can implement "Comparable" so that you can determine how to compare them. You will need to implement the compareTo() method. Something like that:

 public class Example implements Comparable<Example> { private int integerVal = <a value>; public int compareTo(Example exampleObject) { return exampleObject.integerVal - this.integerVal; } } 

Check out this link , or rather a class that starts as follows:

 public class Fruit implements Comparable<Fruit>{ 
+2
source

If you want to sort objects ...

 Example e; int min=-1; // assuming the list has +ve numbers only for (Example elem : yourList) { if ( elem.gtVaribale() <= min ) //assuming you have variable field in your object { e = elem; min = elem.getVariable(); } } yourList.remove(e); //repeat this for remaining elements of the list //you can create another sorted list, and do sortedList.add(e), so that sortedList //have objects in ascending order (of the variable you want to sort) of objects you had in yourList 

This is just pseudo code, and I did not compile it.

+1
source

Here you have to override the comparable method for the Example class. You must tell the compiler how it should compare your e variable with its list items in order to remove it.

0
source

Source: https://habr.com/ru/post/944205/


All Articles