Hello again, I am attempting to create a company with employees that each have individual ID's according to a lab paper. I've got most of it done, except I am confused on what exactly to do regarding putting a for loop, iterator, and hashmap in the same method. I have never used a Hashmap before and don't understand iterators well, so assistance would be appreciated please. I say hashmap as a whole, even if my problem is within the keyset.
#Assistance creating Iterators and Hashmaps in BlueJ
1 messages · Page 1 of 1 (latest)
<@&987246399047479336> please have a look, thanks.
I don't know exactly what I'm iteratoring, am I doing it like a ++ to search all the values?
I put it on employees but still got an error of unknown type.
Usually the errors I get
Please don't post code as screenshots.
It's hard to read and prevents copying and pasting
I will copy it here
public void removeIds(String id)
{
boolean found = false;
id = formatString(id);
if(id == null || id.isEmpty())
{
found = false;
System.out.println("No valid id found.");
}
for(Iterator<employees> it = employees.iterator();
it.hasNext(); )
{
}
}
}
idk how to get the monospace font
public class Company
{
private static final int min = 100;
private static final int max = 999;
private String name;
private HashMap<String, String> employees;
private Random randomGenerator;
Please use this format for posting code:
```java
// Example java program
int value = 5;
System.out.println(value);
```
Which results in:
// Example java program
int value = 5;
System.out.println(value);
For syntax highlighting, you have to add the name of the language after the three backticks, like ```java. Please make sure to use exactly this format, so no space between the backticks and the language name, and a newline before the code starts. If done right, the syntax highlighting will even be applied to your text as you type, before sending.
taldennz • used /tag id: code
·
public void removeIds(String id)
{
boolean found = false;
id = formatString(id);
if(id == null || id.isEmpty())
{
found = false;
System.out.println("No valid id found.");
}
for(Iterator<employees> it = employees.iterator();
it.hasNext(); )
{
}
}
} ```
I’m typing on phone rn so i’m slowly doin it
java public class Company { private static final int min = 100; private static final int max = 999; private String name; private HashMap<String, String> employees; private Random randomGenerator;
Detected code, here are some useful tools:
Formatted code
public class Company {
private static final int min = 100;
private static final int max = 999;
private String name;
private HashMap<String, String> employees;
private Random randomGenerator;
employees is a HashMap<Stirng, String>. You can iterate over it's entries employees.entrySet(). The element type is Map.Entry<String, String>.

You can iterate over the entries with an explicit iterator, or using the enhanced-for statement.
for (Iterator<Map.Entry<String, String>> iterator = employees.entrySet().iterator(); iterator.hasNext(); ) {
Map.Entry<String, String> entry = iterator.next();
...
}
vs
for (Map.Entry<String, String> entry : employees.entrySet()) {
...
}
I see so the map.entry is the type I would have to use
Yes, or you just write var and let Java deduce it for you
Yes, it's the key/value container that each entry in entrySet() uses.
Well I need to figure it out so i don’t think var is the way to go unless it’s just a temporary local variable
what? that doesn't make sense
var will save you writing the type, but that's still the type of variable... Sometimes var is the more readable choice.
I see so it’s more of a formatting thing
Syntactic sugar
for (var iterator = employees.entrySet().iterator(); iterator.hasNext(); ) {
var entry = iterator.next();
...
}
vs
for (var entry : employees.entrySet()) {
...
}
var is only usable in a local variable declaration and some lambda parameters.
I am sorry i don’t really understand half of the words experienced people use when talking about code 😭😭
And you might want to name it idNameEntry if you use var, if the type and content isn't clear from context.
Don't try to use words you don't understand then.
Expressing yourself in simpler terms will not only be beneficial to us understanding you, but also to you as we can easier judge your skill level and talk to you on a level that's best for you (hope you don't take this as an insult 🐒 )
for (var idNameEntry : employees.entrySet()) {
...
}
I will try but unfortunately talking about code is akin to talking in a foreign language because
I will implement the code stated here and see how it goes
Is the map entry or var or whatever it will be named also the key to use? Would that solve the .keySet or would that have to be a separate method?
Maps have entries which are pairs of key/value (accesible via getKey() and getValue() on the entry). keySet() is set of just the keys, values() is a collection of just the values. Which is the best to use depends on your needs.
Alright so I used
java ```
for(var Iterator = employees.entrySet().iterator(); iterator.hasNext(); )
{
} ```
I am getting an error with the iterator.hasNext() saying that it is an unknown type
Also swapping out var with temp causes an error as well, why is that?
You've named the variable Iterator not iterator, so iterator is an unknown variable in iterator.hasNext() .
Ah i see just case sensitive issues then
And also, for the entrySet, what does that do? Like does it set the key to be employees or something, making it so i dont need a separate statement to set the key?
Or is that just not what it does
With entryset you get a collection of the entries. One entry is the key and value respectively.
I see, so this is creating the entries
But there is no key created by this, and I have to set the key so that when that specific entry is entered, it gets the value?
I don't really know what I'm saying sorry 😭
The map contains entries. Each entry contains a key and a value.
entrySet() returns a set of the entries, and your iterator walks over the set giving you an entry at a time. For each entry you can check its key.
I see so creating an entry automatically creates key with it as wll
so rather than setting a value, it is a set of values
You can think of the entry as being created when you put a key and value into the map. entrySet is just returning them.
That makes sense
I will continue to mess around with this map and set stuff and will likely send more code if it doesn't work
Java ```
for (var iterator = employees.entrySet().iterator(); iterator.hasNext(); )
{
if(var.equalsIgnoresCase(id))
{
}
} ```
Detected code, here are some useful tools:
Formatted code
for (var iterator = employees.entrySet().iterator(); iterator.hasNext(); ) {
if (var.equalsIgnoresCase(id)) {
}
}
var is being said that it is an unknown variable, why is that? woudl I put iterator.equalsIgnoresCase(id) instead?
var is a placeholder for the type. iterator is the name of the variable being declared.
I see, so iterator shall be there then
When I did that, it gabe me equalsIgnoresCase was an undeclared method
that's weird
The iterator is an iterator of entries, not an entry itself.
Do I need to create an entry to put in there?
When you add something to a map an entry is created automatically.
for (var idNameEntryIterator = employees.entrySet().iterator(); idNameEntryIterator.hasNext(); ) {
var idNameEntry = idNameEntryIterator.next();
if (idNameEntry.equalsIgnoresCase(id)) {
...
}
}
Hence my point earlier that using var really means being more precise about the variable name.
I see so var doesn't really mean anything to the actual code and can be removed with no problems, it's just for easy reading
I understand what you said now
You can specify the real type, or use var to infer it. However by not expressing the type, readability can suffer if the name is not clear
It's probably a bad idea to teach var to a beginner guys
My instructions are as follows
Add void removeIds(String id) to remove ALL mappings in employees where the value matches the id search parameter and:
MUST use a local variable to keep track if a match was found
MUST also have check if id parameter is null or empty
MUST use formatString to format the id input parameter
MUST use a for loop, .keySet and .iterator to iterate thru all employees
Check if each employee id value is equal (ignoring case) to the search id
MUST use the Iterator.remove to remove id matching mappings
MUST print heading with name & id for EACH removed employee
Only after the entire search is completed (THUS … outside of loop), check if no matches found and print “NO employees with id: <id>”
I just need to get the iterator and key done and after than I can do this
I recommend taking a look at: https://docs.oracle.com/en/java/javase/23/docs/api/java.base/java/lang/Iterable.html .
declaration: module: java.base, package: java.lang, interface: Iterable
Oh this website i remember it
There you can see the subinterfaces, and available methods.
I dont really understand
Which bit?
I don't understand exactly what it is saying for the foreach
default void forEach(Consumer<? super T> action)
What is a super T
a generic
What is a generic?
if you use Iterable<String>, then T will become String
Is that the same Iterator?
wdym
For learning Java, we recommend MOOC.
It is a completely free introductory Java course created by the University of Helsinki, it is a great way to learn Java from the ground up.
Visit MOOC here:
https://java-programming.mooc.fi
(the course is available in both English and Finnish)
- The MOOC teaches a broad introduction to programming in Java in two parts - one at beginner, and another at intermediate level.
The end of the course is marked by creating your own Asteroids game clone! - The MOOC allows using features up to Java 11 - you can install Temurin OpenJDK 11 from the Adoptium project.
- To submit exercises for evaluation, you need to configure an Editor/IDE (Integrated Development Environment) with the TMC Plugin.
The course instructions will suggest to use TMCBeans/NetBeans or VS Code for the course, but you can also use IntelliJ, which we generally recommend.
- TMCBeans/NetBeans is the easiest to configure - but has the most dated user experience
- VS Code is very popular as an editor, but it is quite new for Java Development. Some extra configuration is needed.
- IntelliJ arguably has the best user experience and is most widely used Java IDE by professionals.
IntelliJ requires installing a version no newer than2023.1- because the IntelliJ TMC Plugin doesn't work with newer installs.
The IntelliJ Community version is completely free and all you need to install the TMC plugin.
To use IntelliJ with the MOOC, simply install the TMC plugin by opening IntelliJ -> File -> Settings -> Plugins and searching for TMC. You will then be able to use IntelliJ to complete MOOC.
simon_verhoeven • used /tag id: mooc
·
About the course - Java Programming
Is Iterable an Iterator
It might be worth checking this out.
I’ve started doing that
It’s quite extensive so I’m not far in
Also on W3schools
no, an Iterable is a supplier of iterator
😭 In this case I might not need it then
The requirements (which it helps to know about) say you must explicitly use an iterator... so ignore my comments about the enhanced-for ("for each"), you can't use it.
This is the pattern you'd be using...
for (var idNameEntryIterator = employees.entrySet().iterator(); idNameEntryIterator.hasNext(); ) {
var idNameEntry = idNameEntryIterator.next();
if (idNameEntry.equalsIgnoresCase(id)) {
...
}
}
(assuming the course doesn't mind the use of 'var', some do)
You'll want to see if the entry matches, and if it does, remove the entry from the iterator.
If the course does mind var, what would I change? would it become that IdNameEntry from before?
nevermind that
where it is written that you have to use var ?
Do you have to use var or not ?
There is nothing saying I cannot use it
Then please don't use it
To expand a bit on Alethreon's remark, while var is certainly useful it's important that you're able to infer what the result of your methods are to properly grasp what's going on.
Hm I'm still getting the same error as before with the equals ignores case not working
Which I will not be able to do unfortunately at the moment 😭
Hence their suggestion.
There's nothing wrong with that, we all had to learn sometime.
And without var all the code falls apart, this is a puzzling situation
then fix it
Just a bit of advice, when you press ctrl and hover and hover over a method you can see its signature.
I think I know the issue. Are you calling equalsIgnoreCase on the entry? You need to call key or value on it first.
Alright I'm going back to square 1 with a completely empty code because again without var it gets broken and there is a way without var correct
just ask your ide to remove var
and it's not like it is difficult to do it yourself
what is an ide
just replace var by the type it is supposed to use
Integrated Development Environment.
Is the type supposed to be an int? Since it is an ID right
look at how it is declared
mouse over it
What does that mean? If I try to hover over it but nothing happen
even if i hold ctrl like simon said
Without var it's just a little more verbose. The type of employees is HashMap<String, String> so the type of the entry is Map.Entry<String, String> and an iterator of those entries is Iterator<Map.Entry<String, String>>.
for (Iterator<Map.Entry<String, String>> iterator = employees.entrySet().iterator(); iterator.hasNext(); ) {
Map.Entry<String, String> entry = iterator.next();
if (entry.equalsIgnoresCase(id)) {
...
}
}
Alright I was multitasking for a moment so i couldnt properly pay attention
i don't know which program you are using but BlueJ does not have that
I see, I'll use that for non class related coding then
This is unfortunately what my class uses
does it at least have ctrl+click on a variable or method ?
This is what a normal method looks like inside blueJ
I tried control cllicking but nothing happened
Alright so based off this code it works, but the equalsignorescase is being called on the entry like simon said so it is not working
Now how would I call it on the key?
and also, HashMap<String, String> is what employees is, yet putting it in replacement of that doesn't work
You can call methods on an entry.
Like I said you can ask the key and value of an entry.
So would I need to implement something that gets the key and value from the entry, then call it on that?
declaration: module: java.base, package: java.util, interface: Map, interface: Entry
You really should take a look at the methods of what you're using.
Oughhh this is just like drawing where everything requires each other but i dont have a foundation to start with because everything requires each other
No, it's like a chainlink where you just have to go from link to link.
So you get an entry, and you can do something on that.
Looking at the documentation I linked, which methods might be helpful?
Most likely the getKey? Then I can get the key and call the equalsignorescase on that
The getKey method already returns the key.
And what will the data type of your key be?
Assuming the key is an Id, int? If it's not that, a string
How would you be able the know what type your key and value are respectively?
using the getKey and getValue returns them
No, how would you be able to know the data type of your key and value respectively?
Perhaps the same as the hashmap?
What does an entry represent?
In this case, an employee i think, so that should be called an Element correct?
No.
We called entrySet() on your map, so an entry represents one entry of your hashmap.
Thus you key and value are that respectively.
I thihk i've found a diagram
Is an entry seriously a key and value combined? Is that aall it represents or am I missing something?
There are very few things that make me feel as dumb as coding does.
So the entry itself doesn't have a datatype, but the key and value do
It's just getting the hang of things.
And it does: Map.Entry<K,V>.
Where K is the data type of your key, and V of your value.
It's just following the flow of your logic.
Applying this information is the most difficult
so if entry is not the correct answer to put in, there must be a sort of method to put in there
like searchID or something
Any time anything valid is put in, the equalsIgnoresCase is an error
Hang on is it equalsIgnoreCase or equalsIgnoresCase
Oh. I had to put
id.equalsIgnoresCase(entry.getKey())