I want to find 10 max values of a hashmap and i want others to be united into a single value called "Altri", in english it means others.
How can I do this?
I tried with Collections.max(collection) after defining Collection collection=map.values() but it doesn't work. When I debug it, I see it takes one value that it isn't the higher.
Can anyone help me? Thank's in advance
for that you have to iterate over the hashmap like that:
Map.Entry<Foo, Bar> maxEntry = null;
for (Map.Entry<Foo, Bar> entry : map.entrySet())
{
if (maxEntry == null || entry.getValue().compareTo(maxEntry.getValue()) > 0)
{
maxEntry = entry;
}
}
Map<T, T> map = new TreeMap<T, T>(yourMap);
It will give you sorted data. (natural sorting 1,2,3....100)
Then read last 10 values from map.
You will get 10 MAX values
or use
SortedMap<T,T> instead of Map
it will return sorted data
Related
I am displaying list of check-boxes in horizontal RecyclerView.
It display values such as {"Rd" , "Gr" , "Yl"} but when user selects any of this value it should return {"RED" , "GREEN" , "YELLOW")
How can I bind these two value that show and return differently?
I am taking display values from R.string-arry
I created another string-array of actual values, and when user checked any of checkboxes I get that ID and replaced it with actual values.
For e.g. If user has selected "Gr" I get ID=1 then replaced with actual string-array
But this only works when code-color and original-color are in order. In my app I sometimes use Red,green,blue or sometimes green,yellow,blue. So, this won't help me.
From what I understood, you need a mapping between GR and Green, RD and Red etc.
You can try using a Hashmap.
HashMap<String,String> colourMap = new HashMap<>();
colourMap.put("GR","GREEN");
colourMap.put("RD","RED");
And then you can retrieve the respective value for your colour code:
String colour = colourMap.get("GR");
You can use a HashMap which will bind the two arrays as key value pair
public HashMap<String,String> bindColors() {
HashMap<String,String> map = new HashMap<>();
int length = orginalColors.length;
for (int i = 0; i < length; i++) {
map.put(orginalColors[i], codeColors[i]);
}
return map;
}
And for getting the Colors in code.
HashMap<String, String> keyPair = bindColors();
orginalColorsNewArray = keyPair.keySet().toArray(new String[keyPair.keySet().size()]);
codeColorsNewArray = keyPair.values().toArray(new String[keyPair.values().size()]);
or use .get() function
keyPair.get("YELLOW")
Now it will be easier for you to access the codes by id/position
Hope this helps.
I got two HashMaps with Strings and Integers and both of them carry "20" and 20
When i'm trying to compare them using toString() i always get inequality:
HashMap<String, String> vals = HashMap<String, String>();
HashMap<Integer, Integer> nums = HashMap<Integer, Integer>();
if(nums.get(id).toString() == vals.get("num")) {
Log.i(TAG, "DataBase.updateOrder(): number is the same");
} else {
Log.i(TAG, "DataBase.updateOrder(): number has changed");
}
When i use Integer.valueOf() for String HashMap it works well and they are equal:
if(nums.get(id) == Integer.valueOf(vals.get("num")))
And of course the following record doens't work at all in the way i need:
num.get(id).equals(vals.get("num"))
So the question is why does my first bit of code not work (as i expected)?
use this.equals in your compare the string.
if(nums.get(id).toString().equals(vals.get("num"))) {
Log.i(TAG, "DataBase.updateOrder(): number is the same");
}
you can compare if you parse the String to an int, then you have an integer comparison instead of an string comparison:
if(nums.get(id) == Integer.parseInt(vals.get("num"))) {
Well, it is rather simple:
when you compare by "==" you compare the objects' location in memory. If you want to be sure that "=="
is doing the right thing you need somehow to point one to the other (not the perfect way of saying). Equals on the other hands tries to compute the comparison of the objects' contents.
More about what I have just explained at the link below.
http://www.programmerinterview.com/index.php/java-questions/java-whats-the-difference-between-equals-and/
If you want tor read more about how to implement your own equals on your classes read here.
http://tutorials.jenkov.com/java-collections/hashcode-equals.html
I hope I answered to your question.
Hi I'm still new to java data management.
I have a model object class named Computer which has 3 fields: processor, ram, hddSize.
I created a ArrayList
ArrayList<Computer> myCompList = new ArrayList<Computer>();
Computer comp1 = new Computer();
comp1.setProcessor("1.5 GHZ");
comp1.setRam("512 MB");
comp1.setHddSize("100 GB");
Computer comp2 = new Computer();
comp2.setProcessor("2.5 GHZ");
comp2.setRam("512 MB");
comp2.setHddSize("50 GB");
myCompList.add(comp1);
myCompList.add(comp2);
Now How can I retrieve data at index1 of the ArrayList above?
PS: I know how to do it if its a ArrayList< String> by convert it to String[] and then String[index].
Look at the Javadocs for ArrayList
This is where you should check for simple questions like this. The answer can be found in the "Method Summary" section.
Assuming that you have created getters and setters in your Computer class:
String processor = myCompList.get(1).getProcessor();
String ram = myCompList.get(1).getRam();
String hddSize = myCompList.get(1).getHddSize();
Can't you just go myCompList.get(0); ?
An arraylist of objects is essentially the same as an arraylist of strings. The .get() method returns the specific object at the given index. Here is the documentation for ArrayList.
myCompList.get(index) will return you data on the given index, make sure index number wouldn't be greater than array size, it will give you index out of bounds exception.
I currently have a statement which reads
if(Arrays.asList(results).contains("Word"));
and I want to add at least several more terms to the .contains parameter however I am under the impression that it is bad programming practice to have a large number of terms on one line..
My question is, is there a more suitable way to store all the values I want to have in the .contains parameters?
Thanks
You can use intersection of two lists:
String[] terms = {"Word", "Foo", "Bar"};
List<String> resultList = Arrays.asList(results);
resultList.retainAll(Arrays.asList(terms))
if(resultList.size() > 0)
{
/// Do something
}
To improve performance though, it's better to use the intersection of two HashSets:
String[] terms = {"Word", "Foo", "Bar"};
Set<String> termSet = new HashSet<String>(Arrays.asList(terms));
Set<String> resultsSet = new HashSet<String>(Arrays.asList(results));
resultsSet.retainAll(termSet);
if(resultsSet.size() > 0)
{
/// Do something
}
As a side note, the above code checks whether ANY of the terms appear in results. To check that ALL the terms appear in results, you simply make sure the intersection is the same size as your term list:
resultsSet.retainAll(termSet);
if(resultSet.size() == termSet.size())
You can utilize Android's java.util.Collections
class to help you with this. In particular, disjoint will be useful:
Returns whether the specified collections have no elements in common.
Here's a code sample that should get you started.
In your Activity or wherever you are checking to see if your results contain a word that you are looking for:
String[] results = {"dog", "cat"};
String[] wordsWeAreLookingFor = {"foo", "dog"};
boolean foundWordInResults = this.checkIfArrayContainsAnyStringsInAnotherArray(results, wordsWeAreLookingFor);
Log.d("MyActivity", "foundWordInResults:" + foundWordInResults);
Also in your the same class, or perhaps a utility class:
private boolean checkIfArrayContainsAnyStringsInAnotherArray(String[] results, String[] wordsWeAreLookingFor) {
List<String> resultsList = Arrays.asList(results);
List<String> wordsWeAreLookingForList = Arrays.asList(wordsWeAreLookingFor);
return !Collections.disjoint(resultsList, wordsWeAreLookingForList);
}
Note that this particular code sample will have contain true in foundWordInResults since "dog" is in both results and wordsWeAreLookingFor.
Why don't you just store your results in a HashSet? With a HashSet, you can benefit from hashing of the keys, and it will make your assertion much faster.
Arrays.asList(results).contains("Word") creates a temporary List object each time just to do linear search, it is not efficient use of memory and it's slow.
There's HashSet.containsAll(Collection collection) method you can use to do what you want, but again, it's not efficient use of memory if you want to create a temporary List of the parameters just to do an assertion.
I suggest the following:
HashSet hashSet = ....
public assertSomething(String[] params) {
for(String s : params) {
if(hashSet.contains(s)) {
// do something
break;
}
}
}
I have an unsorted List of Users and a sorted list of Users id. Id is a string.
I want to sort first list by second. How to do that in Kotlin?
data class User(val name : String, val id : String)
val unsorted = listOf<User>(
User("Max", "b12s11"),
User("Joe", "dj1232"),
User("Sam", "23d112"),
User("Tom", "k213i1")
)
val sorted = listOf<String>(
"dj1232",
"b12s11",
"k213i1",
"23d112"
)
// what I need
val result = listOf<User>(
User("Joe", "dj1232"),
User("Max", "b12s11"),
User("Tom", "k213i1"),
User("Sam", "23d112")
)
Shorter solution:
val result = unsorted.sortedBy { sorted.indexOf(it.id) }
Although the other answers show a solution to your problem, it seems to me that a Map<String, User> might better fit the purpose, e.g.:
val usersByid = unsorted.associateBy { it.id }
val result = sorted.mapNotNull {
usersById[it]
}
I assume that every id is only once in the list, therefore I used associateBy. Otherwise it wouldn't be an id for me ;-)
The main difference between this solution and others is that this solution only returns the entries that are also in the sorted-list. Note that if you have users for which you have no id in the sorted-list, this solution omits them, whereas other solutions put those entries at the front of the list. Depends on what you really want.
It could be that this solution is more efficient than the others. Accessing the Map should be much faster then reiterating all the entries over and over again (which both indexOf and first basically do).
I don't know of any Kotlin syntax for doing this, sorting one list by another, but this solution should work for you (the way I understood this question, was that you want to sort according to the Id's in sorted):
val correctList = arrayListOf<User>()
sorted.forEach { sortedId ->
correctList.add(unsorted.first {
it.id == sortedId
})
}
It iterates over your sorted list of Id's and takes the item in the first list (unsorted) which matches that ID and adds it to correctList
Edit: see answer from #Andrei Tanana for a better kotlin answer than mine : sort unsorted collection with another sorted collection's field it's pretty cool :D
Edit2: Thanks to #Roland for pointing out, I can simplify my answer even further with :
val correctList = sorted.map { sortedId -> unsorted.first { it.id == sortedId } }