I have a List of HashMap's which has key of type Integer and value of type Long.
List<HashMap<Integer, Long>> ListofHash = new ArrayList<HashMap<Integer, Long>>();
for (int i = 0; i < 10; i++) {
HashMap<Integer, Long> mMap = new HashMap<Integer, Long>();
mMap.put(Integer.valueOf(i), Long.valueOf(100000000000L+i));
ListofHash.add(mMap);
}
Now, how do I retrieve the key and value from the list of HashMap?
If using Collection class is the solution, please enlight me.
Update 1:
Actually i am getting the value from the database and putting that into a HashMap
public static List<Map<Integer, Long>> populateMyHashMapFromDB()
{
List<HashMap<Integer, Long>> ListofHash = new ArrayList<HashMap<Integer, Long>>();
for (int i = 0; i < 10; i++) {
HashMap<Integer, Long> mMap = new HashMap<Integer, Long>();
mMap.put(Integer.valueOf(getIntFromDB(i)), Long.valueOf(getLongFromDB(i)));
ListofHash.add(mMap);
}
return ListofHash;
}
where getIntFromDB and getLongFromDB can retreive any int and long values respectively.
Now this is where i want to get my values that i got from DB both keys and values
public void getmyDataBaseValues()
{
List<HashMap<Integer,Long>> ListofHash=populateMyHashMapFromDB();
// This is where i got confused
}
ANSWER This is why Peter Lawrey suggested
public class HashMaps {
public static void main(String[] args) {
// TODO Auto-generated method stub
testPrintHashmapValues(putToHashMap());
testPrintHashmapValuesWithList(putToHashMapWithList());
}
public static Map<Integer, Long> putToHashMap() {
Map<Integer, Long> map = new LinkedHashMap<Integer, Long>();
for (int i = 0; i < 10; i++) {
map.put(Integer.valueOf(i), Long.valueOf(200000000000L + i));
}
return map;
}
public static void testPrintHashmapValues(Map<Integer, Long> map) {
for (Map.Entry<Integer, Long> entry : map.entrySet()) {
System.out.println("key: " + entry.getKey() + " value: "
+ entry.getValue());
}
}
public static List<Map<Integer, Long>> putToHashMapWithList() {
List<Map<Integer, Long>> listOfHash = new ArrayList<Map<Integer, Long>>();
for (int i = 0; i < 10; i++) {
Map<Integer, Long> mMap = new HashMap<Integer, Long>();
mMap.put(Integer.valueOf(i), Long.valueOf(100000000000L + i));
listOfHash.add(mMap);
}
return listOfHash;
}
public static void testPrintHashmapValuesWithList(
List<Map<Integer, Long>> listOfHash) {
for (int i = 0; i < 10; i++) {
Map<Integer, Long> map = listOfHash.get(i);
for (Map.Entry<Integer, Long> entry : map.entrySet()) {
System.out.println(i + " hashMap");
System.out.println("key: " + entry.getKey() + " value: "
+ entry.getValue());
}
}
}
}
My Task is done even without creating a List.
Its still not clear to me why you want a list.
public static Map<Integer, Long> populateMyHashMapFromDB() {
Map<Integer, Long> map = new LinkedHashMap<Integer, Long>();
for (int i = 0; i < 10; i++)
map.put(getIntFromDB(i), getLongFromDB(i));
return map;
}
Map<Integer, Long> map = populateMyHashMapFromDB();
Long value = map.get(key);
This collection isn't designed to give you the key/values pairs easily. I fyou need to this functionality I would suggest using a different structure.
Assuming you have a some bad code you cannot change, you can do
List<Map<Integer, Long>> maps = new ArrayList<Map<Integer, Long>>();
Map<Integer, Long> all = new HashMap<Integer, Long>();
for(Map<Integer, Long> map: maps)
all.putAll(map);
for(Map.Entry<Integer, Long> entry: all.entrySet() {
// do something which each key/value.
}
In this example you don't need a List or a Map.
long[] longs = new long[10];
for (int i = 0; i < 10; i++)
longs[i] = i;
int key = 1;
int num = longs[key];
You iterate over the list to get the maps, and then iterate over their key set:
public static void main(String[] args) throws NoSuchAlgorithmException {
List<Map<Integer, Long>> ListofHash = new ArrayList<Map<Integer,Long>>();
for (int i = 0; i < 10; i++) {
Map<Integer, Long> mMap = new HashMap<Integer, Long>();
mMap.put(Integer.valueOf(i), Long.valueOf(100000000000L + i));
ListofHash.add(mMap);
}
for (Map<Integer, Long> map : ListofHash) {
for (Integer key : map.keySet()) {
System.out.println(map.get(key));
}
}
}
Note: I've also changed a little your code, using Map instead of HashMap when possible
Something of this effect:
public static Long getValue(Integer key)) {
for (HashMap<Integer, Long> entry : ListofHash) {
if (entry.containsKey(key)) {
return entry.get(key);
}
}
return null;
}
//Retrieve all key/value
for (HashMap<Integer, Long> entry : ListofHash) {
for (Integer key : entry.keySet()) {
System.out.println("Key : " + key + ", value: " + entry.get(key));
}
}
PS Untested.
I am assuming you are asking how to get it from ArrayList,
ListofHash.get(0).get(Object key);
Object key means whatever Integer key you want
Good Luck!
List<HashMap<Integer, Long>> ListofHash = new ArrayList<HashMap<Integer, Long>>();
for (int i = 0; i < 10; i++) {
HashMap<Integer, Long> mMap = new HashMap<Integer, Long>();
mMap.put(Integer.valueOf(i), Long.valueOf(100000000000L+i));
ListofHash.add(mMap);
}
You have a total of 10 Maps with only one element stored. And those Maps are stored in a List. You can retrieve those Maps and its elements doing this:
public void testPrintHashmapValues() {
List<HashMap<Integer, Long>> listOfHash = new ArrayList<HashMap<Integer, Long>>();
for (int i = 0; i < 10; i++) {
HashMap<Integer, Long> mMap = new HashMap<Integer, Long>();
mMap.put(Integer.valueOf(i), Long.valueOf(100000000000L+i));
listOfHash.add(mMap);
}
for (int i = 0; i < 10; i++) {
Map<Integer, Long> map = listOfHash.get(i);
for (Map.Entry<Integer, Long> entry : map.entrySet()) {
System.out.println(i + " hashMap");
System.out.println("key: " + entry.getKey() + " value: " + entry.getValue());
}
}
}
Also the variables should not start with uppercase (ListOfHash). Even though java won't complain it is a bad practice and difficult to read code like that because one might think it's a class name instead of a variable.
Related
I have a list of users (stored in a properties file) that have a level. I sort the users by their level and then send the sorted list back to the guild. I paginate the list, but its still showing all of the users instead of just 10 per page.
Map<String, Integer> unsortedMap = new HashMap<String, Integer>();
for (String key : prop.stringPropertyNames()) {
String value = prop.getProperty(key);
unsortedMap.put(key, Integer.valueOf(value));
}
Map<String, Integer> sortedMap = sortByValue(unsortedMap);
EmbedBuilder eb = new EmbedBuilder();
eb.setTitle("aaaaaaaaaaaa");
ArrayList<Page> pages = new ArrayList<>();
for (Map.Entry<String, Integer> entry : sortedMap.entrySet()) {
String key = entry.getKey();
int value = entry.getValue();
if (key.contains(".level")) {
User users = ctx.getJDA().retrieveUserById(key.replace(".level", ""), true).complete();
eb.addField(users.getName(), String.valueOf(value), false);
}
}
for (int i = 0; i < sortedMap.size(); i++){
pages.add(new InteractPage(eb.build()));
}
channel.sendMessageEmbeds((MessageEmbed) pages.get(0).getContent()).queue(success -> {
Pages.paginate(success, pages, true);
});
}
private static Map<String, Integer> sortByValue(Map<String, Integer> unsortedMap) {
List<Map.Entry<String, Integer>> list = new LinkedList<Map.Entry<String, Integer>>(unsortedMap.entrySet());
Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() {
#Override
public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
return (o2.getValue().compareTo(o1.getValue()));
}
});
Map<String, Integer> sortedMap = new LinkedHashMap<String, Integer>();
for (Map.Entry<String, Integer> entry : list) {
sortedMap.put(entry.getKey(), entry.getValue());
}
return sortedMap;
Partition the for loop into smaller parts using the for loop. Initialize the int outside of the loop and then increment the int for every entry and then divide the int by how many items you want displayed on the list. Ex:
int i = 0;
for (Map.Entry<String, Integer> entry : sortedMap.entrySet()) {
i++;
if (i % 6 == 0) {
//add page here
I have this program and I want to gather values in ArrayList operatCible and values in Table employeeYearsOfService and I want to stock the result in HashMap<String,integer> witch contains RowKey and result.
I don't know how to do it. This what I want
Code
public class collaborativAlgorithme {
Table<String, String, Double> employeeYearsOfService =
HashBasedTable.create();
public static void main(String[] args) {
List<Double> operatCible = new ArrayList<Double>();
operatCible.add(4.1);
operatCible.add(5.0);
System.out.println(operatCible);
Table<String, String, Double> employeeYearsOfService =
HashBasedTable.create();
employeeYearsOfService.put("AT&T", "Stacy Lerner", 1.4);
employeeYearsOfService.put("Microsoft", "Stacy Lerner", 3.5);
employeeYearsOfService.put("Microsoft", "Bill Smith", 13.2);
employeeYearsOfService.put("Google", "Stacy Lerner", 11.5);
employeeYearsOfService.put("AT&T", "Bill Smith", 2.0);
employeeYearsOfService.put("Google", "Bill Smith", 9.75);
System.out.println(employeeYearsOfService.rowKeySet());
HashMap<String,Integer> result=new HashMap<String,Integer>;
System.out.println(employeeYearsOfService);
Map<String, Double> attEmployees = employeeYearsOfService.row("AT&T");
for (Map.Entry<String, Double> employee : attEmployees.entrySet()) {
// what i do??
// sum values arraylist and values table
System.out.println("Employee Name: " + employee.getKey() + ", Years
of Service: " + employee.getValue());
}
}
}
I solved my problem
And I add something else as (sqrt)....
this is the code
int k = 0;
Double sum = 0.0;//cosine similarity
Double sum2 = 0.0;
System.out.println(employeeYearsOfService);
for (String key : employeeYearsOfService.rowKeySet()) {
HashMap<String, Double> hm = new HashMap<String, Double>();
for (Entry<String, Double> employee :
employeeYearsOfService.row(key).entrySet()) {
sum += employee.getValue() * operatCible.get(k);
sum2+=employee.getValue();
k++;
}
k = 0;
System.out.println(sum);
System.out.println("----");
System.out.println(sqrt(sum2));
hm.put(key, sum);
sum = 0.0;
System.out.println(hm);
}
}
you ca dou that
HashMap<String, Double> hm = new HashMap<String, Double>();
System.out.println(employeeYearsOfService);
for (String key : employeeYearsOfService.rowKeySet()) {
for (Entry<String, Double> employee :
employeeYearsOfService.row(key).entrySet()) {
sum += employee.getValue() + operatCible.get(k);
k++;
}
k = 0;
System.out.println(sum);
hm.put(key, sum);
}
This question already has answers here:
Sort a Map<Key, Value> by values
(64 answers)
Closed 7 years ago.
Forgive me if it seems simple but I couldn't figure it out easily. I thought about using a loop but was wondering if anybody knows an easier way: I have:
Map<String, Integer> map = new HashMap<>();
map.put("ClubB", 1);
map.put("ClubA", 2);
map.put("ClubC", 2);
map.put("ClubD", 2);
map.put("ClubE", 3);
map.put("ClubF", 2);
map.put("ClubG", 2);
I need to get keys or values at specific index in my tests. For example I need to get the key and value at index 3 etc. The reason is that I use a comparator and sort the Map and would like to show that the value at a specific index has changed.
Thanks for any ideas.
UPDATE:
I used:
HashMap leagueTable = new HashMap();
Map<String, Integer> map = sortByValues(leagueTable);
public <K extends Comparable<K>, V extends Comparable<V>> Map<K, V> sortByValues(final Map<K, V> map) {
Comparator<K> valueComparator = new Comparator<K>() {
public int compare(K k1, K k2) {
int compare = map.get(k2).compareTo(map.get(k1));
if (compare == 0) {
return k1.compareTo(k2); // <- To sort alphabetically
} else {
return compare;
}
}
};
Map<K, V> sortedByValues = new TreeMap<K, V>(valueComparator);
sortedByValues.putAll(map);
return sortedByValues;
}
I then used aloop to print out values:
for (Map.Entry<String, Integer> entry : map.entrySet()) {
System.out.println( entry.getKey() + ", " + entry.getValue() );
}
Ended up using a for loop and comparing with what I already had added to the Map:
HashMap<String, Integer> map = new HashMap<>();
map.put("ClubD", 3);
map.put("ClubB", 1);
map.put("ClubA", 2);
map.put("ClubC", 2);
map.put("ClubE", 2);
map.put("ClubF", 2);
map.put("ClubG", 2);
Map<String, Integer> mapResult = instance.sortByValues(map);
String expectedResultKey = "ClubB";
int expectedResultValue = 1;
String resultKey = "";
int resultValue = 0;
for (Map.Entry<String, Integer> entry : map.entrySet()) {
resultKey = entry.getKey();
resultValue = entry.getValue();
}
assertSame(expectedResultKey, resultKey);
HashMap's don't have indices. They just store data in key-value pairs.
Instead of map being a Map, why don't you use a 2D array? (And give it a more appropriate name)
String[][] array = new String[3][3];
array[3] = new String[] { "ClubD" };
array[1] = new String[] { "ClubB" };
array[2] = new String[] { "ClubA", "ClubC", "ClubE", "ClubF", "ClubG" };
System.out.println(array[3][0]);
and then if you wanted to loop through that array, you would just do:
for (int a = 0; a < array.length; a++)
for (int b = 0; b < array[a].length; b++)
if (array[a][b] != null)
System.out.println("array["+a+"]["+b+"] is: "+array[a][b]);
I need to reverse the order of what the below method returns. For example if it
returns:
1=ball, 2=save, 3=take 4=till
I want to reverse and return:
1=till, 2=take, 3=save, 4=ball
My method is:
public Map<Integer, String> returnMapOfValues(ArrayList<String> wordsList) {
int getFrequencyValue = 0;
Set<String> uniqueSetWords = new HashSet<String>(wordsList);
for (String temp : uniqueSetWords) {
getFrequencyValue = Collections.frequency(wordsList, temp);
//prints the Collection of words and they frequency, For testing only
//System.out.println(temp + ":" + Collections.frequency(wordsList,
//temp));
map.put(getFrequencyValue, temp);
getFrequencyValue = 0;
}
return map;
}
Please check if the below code I've written is useful for you as a reference:
public void reverseMap()
{
NavigableMap<Integer,String> map = new TreeMap<Integer,String>();
LinkedHashMap<Integer,String> reverseMap = new LinkedHashMap<Integer,String>();
map.put(1,"Apple");
map.put(2,"Ball");
map.put(3,"Cat");
NavigableSet<Integer> keySet = map.navigableKeySet();
Iterator<Integer> iterator = keySet.descendingIterator();
Integer i;
while(iterator.hasNext())
{
i = iterator.next();
reverseMap.put(i,map.get(i));
}
System.out.println(reverseMap);
}
//map to arrange inizialized
LinkedHashMap<String,object> mta;
//transforms into arrayList hashmap keys and values
ArrayList<Object> valuesTMP=new ArrayList<Object>(mta.values());
ArrayList<String> keysTMP;
keysTMP=new ArrayList<String>(mta.keySet());
//reverse
Collections.reverse(valuesTMP);
Collections.reverse(keysTMP);
LinkedHashMap <String,Object> mtarranged=new LinkedHashMap<String, Object>();
int index=0;
for( String key : keysTMP){
mtarranged.put(key,valuesTMP.get(index));
index++;
}
To answer this question, we need to know how you're iterating the Map since Maps don't have entry order. However, you may try using a TreeMap which has the method descendingMap:
public Map<Integer, String> returnMapOfValues(ArrayList<String> wordsList) {
TreeMap<Integer, String> map = new TreeMap<Integer, String>();
int getFrequencyValue = 0;
Set<String> uniqueSetWords = new HashSet<String>(wordsList);
for (String temp : uniqueSetWords) {
getFrequencyValue = Collections.frequency(wordsList, temp);
//prints the Collection of words and they frequency, For testing only
//System.out.println(temp + ":" + Collections.frequency(wordsList,
//temp));
map.put(getFrequencyValue, temp);
getFrequencyValue = 0;
}
return map.descendingMap();
}
Edit: From your comment, your intent is more clear. A TreeMap will help you with your goal because it is a Map ordered by the natural order of the keys.
I've made some changes to the code. Please check if this is OK for you now.
public void reverseMap()
{
NavigableMap<Integer,String> map = new TreeMap<Integer,String>();
LinkedHashMap<Integer,String> reverseMap = new LinkedHashMap<Integer,String>();
map.put(1,"Apple");
map.put(2,"Ball");
map.put(3,"Cat");
NavigableSet<Integer> keySet = map.navigableKeySet();
Iterator<Integer> forwardIterator = keySet.iterator();
Iterator<Integer> reverseIterator = keySet.descendingIterator();
Integer i;
Integer j;
while(forwardIterator.hasNext())
{
i = forwardIterator.next();
j = reverseIterator.next();
reverseMap.put(i,map.get(j));
}
System.out.println(reverseMap);
}
Please find the below code and Let me know Which is suitable for you ...
int iterationValue = 0;
List<String> stringList = new LinkedList<String>();
stringList.add("ball");
stringList.add("save");
stringList.add("tick");
Map<Integer, String> map = new HashMap<Integer, String>();
for (String temp : stringList) {
map.put(iterationValue++, temp);
}
// Input MAP
System.out.println(map); // {0=ball, 1=save, 2=tick}
Collections.reverse(stringList);
iterationValue = 0;
for (String temp : stringList) {
map.put(iterationValue++, temp);
}
// Output MAP
System.out.println(map); // {0=tick, 1=save, 2=ball}
I'm trying to get results HashMap sorted by value.
This is HashMap's keys and values:
map.put("ertu", 5);
map.put("burak", 4);
map.put("selin", 2);
map.put("can", 1);
I try to get results like this:
1 = can
2 = selin
4 = burak
5 = ertu
Here is my code:
import java.util.*;
public class mapTers {
public static void main(String[] args) {
HashMap<String, Integer> map = new HashMap<String, Integer>();
map.put("ertu", 5);
map.put("burak", 4);
map.put("selin", 2);
map.put("can", 1);
Integer dizi[] = new Integer[map.size()];
Set anahtarlar = map.keySet();
Iterator t = anahtarlar.iterator();
int a = 0;
while (t.hasNext()) {
dizi[a] = map.get(t.next());
a++;
}
Arrays.sort(dizi);
for (int i = 0; i < map.size(); i++) {
while (t.hasNext()) {
if (dizi[i].equals(map.get(t.next()))) {
System.out.println(dizi[i] + " = " + t.next());
}
}
}
}
}
You can sort the entries as follows (but note this won't sort the map itself, and also HashMap cannot be sorted) -
List<Map.Entry<String, Integer>> entryList = new ArrayList<Map.Entry<String, Integer>>(map.entrySet());
Collections.sort(entryList, new Comparator<Map.Entry<String, Integer>>() {
#Override
public int compare(Entry<String, Integer> o1, Entry<String, Integer> o2) {
return o1.getValue().compareTo(o2.getValue());
}
});
Every time that you call t.next(), the iterator's pointer is moved forward. Eventually, the iterator reaches the end. You need to reset the iterator. Also, calling t.next() twice moves the pointer twice.
Here's my solution:
import java.util.*;
public class mapTers
{
public static void main(String[] args)
{
HashMap<String, Integer> map = new HashMap<String, Integer>();
map.put("ertu", 5);
map.put("burak", 4);
map.put("selin", 2);
map.put("can", 1);
Integer dizi[] = new Integer[map.size()];
Set anahtarlar = map.keySet();
Iterator t = anahtarlar.iterator();
int a = 0;
while (t.hasNext())
{
dizi[a] = map.get(t.next());
a++;
}
Arrays.sort(dizi);
for (int i = 0; i < map.size(); i++)
{
t = anahtarlar.iterator();
while (t.hasNext())
{
String temp = (String)t.next();
if (dizi[i].equals(map.get(temp)))
{
System.out.println(dizi[i] + " = " + temp);
}
}
}
}
}
You cannot do that from a Map. At least not directly.
Retrieve the keys/entries, get all the map data in a more suitable structure (hint: a class that encapsulates both attributes and is is stored in a sortable (hint2: SortedSet, List)) and sort.
Do not forget to extend Comparable (and implement compareTo) or, otherwise, create a Comparator.
This is one of the solutions take from: https://stackoverflow.com/a/13913206/1256583
Just pass in the unsorted map, and you'll get the sorted one.
private static Map<String, Integer> sortByComparator(Map<String, Integer> unsortMap, final boolean order) {
List<Entry<String, Integer>> list = new LinkedList<Entry<String, Integer>>(unsortMap.entrySet());
// Sorting the list based on values
Collections.sort(list, new Comparator<Entry<String, Integer>>() {
public int compare(Entry<String, Integer> o1, Entry<String, Integer> o2) {
if (order) {
return o1.getValue().compareTo(o2.getValue());
}
else {
return o2.getValue().compareTo(o1.getValue());
}
}
});
// Maintaining insertion order with the help of LinkedList
Map<String, Integer> sortedMap = new LinkedHashMap<String, Integer>();
for (Entry<String, Integer> entry : list) {
sortedMap.put(entry.getKey(), entry.getValue());
}
return sortedMap;
}
To print, do a simple iteration over the entry set:
public static void printMap(Map<String, Integer> map) {
for (Entry<String, Integer> entry : map.entrySet()) {
System.out.println("Key : " + entry.getKey() + " Value : "+ entry.getValue());
}
}
You probably have the wrong data structure for this problem. Either:
Reverse the map so the integers are the keys and the words the values and make the map a SortedMap, or
Use a bidirectional map as provided by libraries like Google Guava.
Reversed Map
private final SortedMap<Integer, String> TRANSLATIONS;
static {
SortedMap<Integer, String> map = new TreeMap<>();
map.put(1, "can");
// ...
TRANSLATIONS = Collections.unmodifiableSortedMap(map);
}
Guava BiMap
private final BiMap TRANSLATIONS =
new ImmutableBiMap.Builder<String, Integer>()
.put("ertu", 5);
.put("burak", 4);
.put("selin", 2);
.put("can", 1);
.build();
Then, iterate over a sorted version of the key set or value set as needed. For example,
TRANSLATIONS.inverse.get(4); // "burak"
I'm just curious. What language are your strings in?