How to remove null { } map from ArrayList<HashMap<String, String>>? - java

I have a ArrayList<HashMap<String, String>> placesListItems.
When I remove a map from placesListItems, the null map remains. So that my ListAdapter contains null list items.
for (HashMap<String, String> map : placesListItems) {
for (Entry<String, String> entry : map.entrySet()) {
for (int j = 0; j < duplicateList.size(); j++) {
if (entry.getValue().equals(duplicateList.get(j))) {
Iterator iterator = map.entrySet().iterator();
while (iterator.hasNext()) {
Entry<String, String> pairs = (Entry)iterator.next();
System.out.println(pairs.getKey() + " = " + pairs.getValue());
iterator.remove(); // avoids a ConcurrentModificationException
}
}
}
}
}
ListAdapter adapter = new ItemAdapterHome(getApplicationContext, placesListItems);
lv.setAdapter(adapter);
How can I solve this?

What you need to do is add all empty maps in list and remove them all at the end.
List<HashMap<String, String>> mapsToRemove= new ArrayList<HashMap<String, String>>();//list in which maps to be removed will be added
for (HashMap<String, String> map : placesListItems)
{
for (Entry<String, String> entry : map.entrySet())
{
for (int j = 0; j < duplicateList.size(); j++)
{
if(entry.getValue().equals(duplicateList.get(j)))
{
Iterator iterator = map.entrySet().iterator();
while (iterator.hasNext())
{
Entry<String, String> pairs = (Entry)iterator.next();
System.out.println(pairs.getKey() + " = " + pairs.getValue());
iterator.remove(); // avoids a ConcurrentModificationException }
}
}
}
if(map.isEmpty){//after all above processing, check if map is empty
mapsToRemove.add(map);//add map to be removed
}
}
placesListItems.removeAll(mapsToRemove);//remove all empty maps
ListAdapter adapter = new ItemAdapterHome(getApplicationContext, placesListItems);
lv.setAdapter(adapter);
You might need to change the logic a little based on your requirement.

Your problem is that you are emptying maps instead of removing them from the list.
Try the following:
Iterator<Map<String, String>> iterator = placesListItems.iterator();
while (iterator.hasNext()) {
Map<String, String> map = iterator.next();
for (String value : map.values()) {
if (duplicateList.contains(value)) { // You can iterate over duplicateList, but List.contains() is a nice shorthand.
iterator.remove(); // Removing the map from placesListItems
break; // There is no point iterating over other values of map
}
}
}

Related

How can I make a list still contain its elements even after clearing it?

How should I go about setting a key to a list in a foreach loop and then reseting aforementioned list so it takes in other values without clearing it.
Here is my code:
public static Map<String, List<Integer>> trend(Map<String, List<Integer>> companies){
List<Integer> list = new LinkedList<>();
List<Integer> list2 = new LinkedList<>();
Map<String, List<Integer>> finalMap = new HashMap<>();
int difference = 0;
for(Map.Entry<String, List<Integer>> entry : companies.entrySet()) {
list = entry.getValue();
for(int i = 0; i <= list.size() - 1; i++) {
if(i < list.size() - 1) {
difference = list.get(i+1) - list.get(i);
list2.add(difference);
}
}
finalMap.put(entry.getKey(), list2);
list.clear();
list2.clear();
}
return finalMap;
}
If you don't want to clear that list just remove the call to list.clear() for that list.

Get all size of values in a HashMap<String,List<String,String>>

In my HashMap < String,List< String,String>> I saved keys (Name of a building) and values (Id´s from devices in this building).
I just want to get the size of values from each keys in my HashMap but the only size I get is from the first Key,Value pair...Here´s my code
Map<String, List<String>> moduleNamesWithAllParameters = new
HashMap<String, List<String>>();
List<String> parameters = new ArrayList<String>();
List<String> moduleNames = new ArrayList<String>();
Iterator it;
int start = 0, end = 0, mapKeys = 0;
parameters.add("kExmWoEM2HpMA4CT");
parameters.add("ILm1nApv06lDtqva");
parameters.add("gu00xoO5WPTv0SEr");
parameters.add("kX4FIg6c3C10msex");
parameters.add("xUcA4Y5rvqxlg8ju");
parameters.add("TYjydK6AyY7vwYSo");
parameters.add("#");
parameters.add("IDvHK1vXMiDEPxad");
parameters.add("ja0D3LH8ML0mQwZ0");
parameters.add("#");
parameters.add("tKgYRVvguvl3ByRc");
parameters.add("I95sFdAOoUTHjO7Y");
moduleNames.add("Building 1");
moduleNames.add("Building 2");
moduleNames.add("Building 3");
it = parameters.iterator();
for (int i = 0; i < moduleNames.size(); i++) {
do {
end++;
} while (it.hasNext() && !(it.next().equals("#")));
moduleNamesWithAllParameters.put(moduleNames.get(i), parameters.subList(start, end - 1));
start = end;
}
for (String key : moduleNamesWithAllParameters.keySet())
System.out.println(key + " = " + moduleNamesWithAllParameters.get(key));
Entry<String, List<String>> entry;
for (int i = 0; i < moduleNames.size(); i++) {
entry = moduleNamesWithAllParameters.entrySet().iterator().next();
mapKeys = entry.getValue().size();
System.out.println(mapKeys);
}
}
This line:
entry = moduleNamesWithAllParameters.entrySet().iterator().next();
Is constantly creating a new iterator over the entry set of the map and returning the first entry. So you will only ever see the first entry.
You can change the loop to loop over all entries like this:
for (Entry<String, List<String>> entry : moduleNamesWithAllParameters.entrySet()) {
mapKeys = entry.getValue().size();
System.out.println(mapKeys);
}
Assuming you're using Java8 or later:
moduleNamesWithAllParameters.entrySet().stream().forEach((entry) -> {
System.out.println(entry.getValue().size());
});
Replace your last loop with the following:
for (int i = 0; i < moduleNames.size(); i++) {
mapKeys = moduleNamesWithAllParameters.get(moduleNames.get(i)).size();
System.out.println(mapKeys);
}
Or a bit neater:
for(String key : moduleNamesWithAllParameters.keySet()) {
System.out.println(moduleNamesWithAllParameters.get(key).size());
}
Or even neater (Java 8+):
moduleNamesWithAllParameters.stream().forEach(entry ->
System.out.println(entry.getValue().getSize())
);
Or loop using valueSet (since you don't actually use the key):
for(List<String> value : moduleNamesWithAllParameters.valueSet()) {
System.out.println(value.size());
}
Or if you so fancy (Java 8+):
moduleNamesWithAllParameters.valueSet().stream().map(List::size).forEach(System.out::println);
Probleam is happend in this line:
entry = moduleNamesWithAllParameters.entrySet().iterator().next();
entrySet().iterator() is a new object each time it loops.
So you map size only is the first size.

Is there a way to infinitely loop through Map elements in java?

Suppose I have a Map with m elements in it, like the following.
Map<String,Integer> mp = new HashMap<String,Integer>();
mp.put("Delhi",1);
mp.put("Bombay",1);
mp.put("Bangalore",1);
Here, m = 3. I would like to access the map of above elements in a cyclic order for specific number of times n, where n != m. Each time I access the Map I want to get the "next" element in the Map (so that implies that the Map entries are somehow ordered). If I get to the end of the Map I want to start over again at the beginning, since I want in all cases to access the map exactly n times. There is no relationship between n and m. Each time I access a map element I want to increase the value of that element by 1.
For example, given the above Map with 3 elements (m == 3), and supposing I want to access the Map five times in total (n == 5). The following should happen:
step-->String(Key)-->Integer(Value)
1-->Delhi-->2
2-->Bombay-->2
3-->Bangalore-->2
4-->Delhi-->3
5-->Bombay-->3
Any suggestions on this would be appreciated, even change of DataStructure as well.
I am specifically looking to loop through the map elements in tandem with an external loop.
What I don't want: suppose I have a for loop say
for(1 to numberofcycles)
{
for(iterate-->mapelements)
{
//looping mapelements
}
}
I would be looping through the map numberofcycles * numberofmap elements which is not what i am expecting to achieve.
Instead, I would like to achieve to loop through mapelements for exactly numberofcycles in cyclic order and changing/adding 1 to value after each visit.
i.e.
keep iterating through map in cyclic order until specific condition is reached.
As I understand it, you want to make a total of n trips, each one to a different destination, and you're visiting those destinations in a predefined order. How about something like this...
If you want to specify the order independent of the Map
Map<String,Integer> mp = new HashMap<>();
mp.put("Delhi",1);
mp.put("Bombay",1);
mp.put("Bangalore",1);
int numberOfTrips = 5;
List<String> orderOfVisits = Arrays.asList("Delhi", "Bombay", "Bangalore");
Iterator<String> visiterator = orderOfVisits.iterator();
for (int i = 0; i < numberOfTrips; i++) {
// Get a new iterator if we've exhausted the previous one
if (!visiterator.hasNext()) {
visiterator = orderOfVisits.iterator();
}
// Get the correct city and increment the counter
String key = visiterator.next();
mp.put(key, mp.get(key) + 1);
}
// demonstrate that the map contains the correct values
for (Entry<String, Integer> entry: mp.entrySet()) {
System.out.println("Key:" + entry.getKey() + ", Value:" + entry.getValue());
}
If you want the Map to govern the order
To visit the cities in the order in which they were added to the Map, you can do the following:
1) Change the declaration of mp from HashMap to LinkedHashMap:
Map<String,Integer> mp = new LinkedHashMap<>();
2) Iterate over the keyset of the Map:
visiterator = mp.keySet().iterator();
If you want to specify the order with a Comparator
1) Change the declaration of mp to TreeMap, supplying a Comparator:
Map<String,Integer> map = new TreeMap<>(Comparator.naturalOrder());
2) Iterate over the keyset of the Map as in the above example.
All the code
public static void tripsInConfigurableOrder() {
Map<String, Integer> mp = new HashMap<String, Integer>();
mp.put("Delhi", 1);
mp.put("Bombay", 1);
mp.put("Bangalore", 1);
int numberOfTrips = 5;
List<String> orderOfVisits = Arrays.asList("Delhi", "Bombay", "Bangalore");
Iterator<String> visiterator = orderOfVisits.iterator();
for (int i = 0; i < numberOfTrips; i++) {
if (!visiterator.hasNext()) {
visiterator = orderOfVisits.iterator();
}
String key = visiterator.next();
mp.put(key, mp.get(key) + 1);
}
for (Entry<String, Integer> entry : mp.entrySet()) {
System.out.println("Key:" + entry.getKey() + ", Value:" + entry.getValue());
}
}
public static void tripsInNaturalOrder() {
Map<String, Integer> mp = new LinkedHashMap<>();
mp.put("Delhi", 1);
mp.put("Bombay", 1);
mp.put("Bangalore", 1);
int numberOfTrips = 5;
Iterator<String> visiterator = mp.keySet().iterator();
for (int i = 0; i < numberOfTrips; i++) {
if (!visiterator.hasNext()) {
visiterator = mp.keySet().iterator();
}
String key = visiterator.next();
mp.put(key, mp.get(key) + 1);
}
for (Entry<String, Integer> entry : mp.entrySet()) {
System.out.println("Key:" + entry.getKey() + ", Value:" + entry.getValue());
}
}
public static void usingComparator() {
Map<String, Integer> mp = new TreeMap<>(Comparator.naturalOrder());
mp.put("Delhi", 1);
mp.put("Bombay", 1);
mp.put("Bangalore", 1);
int numberOfTrips = 5;
Iterator<String> visiterator = mp.keySet().iterator();
for (int i = 0; i < numberOfTrips; i++) {
if (!visiterator.hasNext()) {
visiterator = mp.keySet().iterator();
}
String key = visiterator.next();
mp.put(key, mp.get(key) + 1);
}
for (Entry<String, Integer> entry : mp.entrySet()) {
System.out.println("Key:" + entry.getKey() + ", Value:" + entry.getValue());
}
}
public static void main(String[] args) {
tripsInConfigurableOrder();
tripsInNaturalOrder();
usingComparator();
}
Map<String,Integer> mp = new HashMap<String,Integer>();
mp.put("Delhi",1);
mp.put("Bombay",1);
mp.put("Bangalore",1);
for (int i = 0 ; i < numberOfCycles; i++){
for (String key : mp.keySet()){
mp.put(key,mp.get(key)+1);
}
}
How about using the while loop and put iteration inside a while loop like this?
Map<String, Integer> map = ...
while (true or some condition)
{
for (Map.Entry<String, Integer> entry : map.entrySet())
{
map.put(key, map.get(key) + 1);
}
if (some condition met)
some condition = false
}
EDIT
I read your edited post and here is a solution to what you want to do.
You could use break to get out of the for loop when you reached maxCycle.
Map<String, Integer> map = ...
int numberOfCycles = 0;
int maxCycle = 10;
while (numberOfCycles < maxCycle)
{
for (Map.Entry<String, Integer> entry : map.entrySet())
{
if (++numberOfCycles < maxCycle)
map.put(key, map.get(key) + 1);
else
break;
}
}
Say you start from 0 and maxCycle is 5. If you have iterated 5 times, it will go to else and call break. After break you will go back to while loop and the exit condition is satisfied.

Reverse Map.key, map.value output

I have this output and it comes out in the opposite order. The last printout is what i want to be the first print out. How can I reverse it? It is a HashMap.
System.out.println();
int c = 0;
System.out.print(newName + "= ");
for (Map.Entry<Integer, Integer> entry : result.entrySet()) {
System.out.print(entry.getValue() + "X^" + entry.getKey());
c++;
if (c != result.size()) {
System.out.print("+");
}
To preserve insertion order when iterating use a LinkedHashMap instead of a HashMap, and to go in reverse do this:
List<Map.Entry<Integer, Integer>> entries = new ArrayList<>(result.entrySet());
Collections.reverse(entries);
for (Map.Entry<Integer, Integer> entry : entries) {
// same body as before
}
Alternatively, we can use a reverse iterator:
List<Map.Entry<Integer, Integer>> entries = new ArrayList<>(result.entrySet());
ListIterator<Map.Entry<Integer, Integer>> iter = entries.listIterator();
while (iter.hasPrevious()) {
Map.Entry<Integer, Integer> entry = iter.previous();
// same body as before
}

how to get hashmap values depends on key

i have this hashmap with string and arraylis:
Map<String, ArrayList<String>> devNameType = new HashMap<String, ArrayList<String>>();
public void kimenetPV(String name){
//létrehozom a nevet
String devName = name;
//létrehozom a kimeneteket tartalmazó arraylistet
ArrayList<String> outputs = new ArrayList<String>();
// 2. hozzáadaom az elemeket
outputs.add("EM A");
outputs.add("EM B");
outputs.add("AOUT1");
outputs.add("AOUT2");
devNameType.put(devName, outputs);
Iterator iter = devNameType.entrySet().iterator();
//kilistázom az elemeket
while (iter.hasNext()) {
Map.Entry mEntry = (Map.Entry) iter.next();
System.out.println(mEntry.getKey() + " : " + mEntry.getValue());
}
}
how can i print all the values?
Sorry for the begginer question i'm using the hashmaps for first time.
You can print the key:value pairs as this:
Iterator<Entry<String, List<String>>> iter = devNameType.entrySet().iterator();
while (iter.hasNext()) {
Entry<String, List<String>> next = iter.next();
List<String> value = next.getValue();
System.out.println("key = " + next.getKey());
System.out.println("values : ");
for (String str : value) {
System.out.println(str);
}
}
for (List<String> value : devNameType.values()) {
... do something with this value
}
For key/value:
for (String key: devNameType.keySet()) {
List<String> values = devNameType.get(key);
... do something with the name and values
}
See http://docs.oracle.com/javase/6/docs/api/java/util/Map.html#values() and
http://docs.oracle.com/javase/6/docs/api/java/util/Map.html#keySet()
With hashMap.values() you get a Collection of all values:
http://developer.android.com/reference/java/util/HashMap.html#values()

Categories

Resources