Reputation: 1387
I have defined a list as:
List<Entry<String, Integer>> list
It has the count of the string. I want to iterate over the list and print all strings/keys that have a count of 1.
This is what I tried:
for (int i=0;i<list.size();i++) {
if(list.get(i) == 1){
System.out.println(list(i));
}
}
I get "Incompatible operand types Map.Entry and int"
Upvotes: 1
Views: 690
Reputation: 26104
You have list of Map.Entry objects. You can iterate the list using below code.
for (Map.Entry<String, Integer> entry:list) {
if(entry.getValue() == 1){
System.out.println("key":+entry.getKey());
System.out.println("value":+entry.getValue());
}
}
Upvotes: 1
Reputation: 726849
You can do it easier with a "foreach" kind of the for
loop, like this:
for (Map.Entry<String,Integer> entry : list) {
if (entry.getValue() == 1) {
System.out.println(entry);
}
}
The idea is to skip the index altogether, and use Java's built-in iterating capabilities to shorten your code.
Upvotes: 6
Reputation: 280122
"Incompatible operand types Map.Entry and int"
That's because you are comparing a Map.Entry
reference with an int
.
You need to get each element of the List
as an Entry
and use its value
property in your if
condition comparison
for (int i=0;i<list.size();i++) {
Entry<String, Integer> e = list.get(i);
if(e.getValue() == 1){
System.out.println(e);
}
}
I don't know why you have a List<Entry>
, but there is probably a better way to iterate over Entry
elements, ie. an Iterator
.
Upvotes: 1
Reputation: 178303
If you must use List<Entry<String, Integer>>
...
You retrieved your Entry<String, Integer>
from the list, but you're comparing it with 1
. You need to go one step further and retrieve the Integer
from the Entry
, presumably with getValue()
.
if(list.get(i).getValue() == 1){
Additionally, list(i)
won't compile. You may want to declare a new variable for holding the result of list.get(i)
so you won't have to call get
twice on the same entry.
Upvotes: 2