#Assistance creating Iterators and Hashmaps in BlueJ

1 messages · Page 1 of 1 (latest)

boreal tusk
#

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.

quartz tokenBOT
#

<@&987246399047479336> please have a look, thanks.

boreal tusk
#

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

west urchin
boreal tusk
#

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;

quartz tokenBOT
#

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.

boreal tusk
#
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(); )
        {
            
        }
        
    }
} ```
vagrant star
#

backstick `

#

@boreal tusk

boreal tusk
#

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;

quartz tokenBOT
distant kernel
#

employees is a HashMap<Stirng, String>. You can iterate over it's entries employees.entrySet(). The element type is Map.Entry<String, String>.

boreal tusk
distant kernel
#

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()) {
    ...
}
boreal tusk
#

I see so the map.entry is the type I would have to use

west urchin
#

Yes, or you just write var and let Java deduce it for you

distant kernel
#

Yes, it's the key/value container that each entry in entrySet() uses.

boreal tusk
#

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

west urchin
#

what? that doesn't make sense

distant kernel
#

var will save you writing the type, but that's still the type of variable... Sometimes var is the more readable choice.

boreal tusk
#

I see so it’s more of a formatting thing

west urchin
#
for (var iterator = employees.entrySet().iterator(); iterator.hasNext(); ) {
    var entry = iterator.next();
    ...
}

vs

for (var entry : employees.entrySet()) {
    ...
}
distant kernel
#

var is only usable in a local variable declaration and some lambda parameters.

boreal tusk
distant kernel
#

And you might want to name it idNameEntry if you use var, if the type and content isn't clear from context.

west urchin
distant kernel
#
for (var idNameEntry : employees.entrySet()) {
   ...
}
boreal tusk
#

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?

distant kernel
#

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.

boreal tusk
#

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?

distant kernel
#

You've named the variable Iterator not iterator, so iterator is an unknown variable in iterator.hasNext() .

boreal tusk
#

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

shrewd galleon
#

With entryset you get a collection of the entries. One entry is the key and value respectively.

boreal tusk
#

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 😭

distant kernel
#

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.

boreal tusk
#

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

distant kernel
#

You can think of the entry as being created when you put a key and value into the map. entrySet is just returning them.

boreal tusk
#

studious 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))
{

        }
    
    } ```
quartz tokenBOT
boreal tusk
#

var is being said that it is an unknown variable, why is that? woudl I put iterator.equalsIgnoresCase(id) instead?

distant kernel
#

var is a placeholder for the type. iterator is the name of the variable being declared.

boreal tusk
#

I see, so iterator shall be there then

#

When I did that, it gabe me equalsIgnoresCase was an undeclared method

#

that's weird

distant kernel
#

The iterator is an iterator of entries, not an entry itself.

boreal tusk
#

Do I need to create an entry to put in there?

shrewd galleon
#

When you add something to a map an entry is created automatically.

distant kernel
#
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.

boreal tusk
#

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

distant kernel
#

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

vagrant star
#

It's probably a bad idea to teach var to a beginner guys

boreal tusk
#

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

shrewd galleon
boreal tusk
#

Oh this website i remember it

shrewd galleon
#

There you can see the subinterfaces, and available methods.

boreal tusk
#

I dont really understand

shrewd galleon
#

Which bit?

boreal tusk
#

I don't understand exactly what it is saying for the foreach

#

default void forEach(Consumer<? super T> action)

#

What is a super T

vagrant star
boreal tusk
#

What is a generic?

vagrant star
boreal tusk
#

Is that the same Iterator?

vagrant star
quartz tokenBOT
#

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 than 2023.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.

About the course - Java Programming

boreal tusk
#

Is Iterable an Iterator

shrewd galleon
#

It might be worth checking this out.

boreal tusk
#

It’s quite extensive so I’m not far in

#

Also on W3schools

vagrant star
boreal tusk
#

😭 In this case I might not need it then

distant kernel
#

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.

boreal tusk
#

If the course does mind var, what would I change? would it become that IdNameEntry from before?

#

nevermind that

vagrant star
boreal tusk
#

But what would var become

#

I didn’t quite understand that sentence

vagrant star
boreal tusk
#

There is nothing saying I cannot use it

vagrant star
boreal tusk
#

Alright then, I will not use it

#

I’ll type in the code and see if I get any errors

shrewd galleon
#

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.

boreal tusk
#

Hm I'm still getting the same error as before with the equals ignores case not working

boreal tusk
shrewd galleon
#

Hence their suggestion.

#

There's nothing wrong with that, we all had to learn sometime.

boreal tusk
#

And without var all the code falls apart, this is a puzzling situation

shrewd galleon
#

Just a bit of advice, when you press ctrl and hover and hover over a method you can see its signature.

vagrant star
#

and depending of your ide

#

you can make it autocomplete the variable types

shrewd galleon
#

I think I know the issue. Are you calling equalsIgnoreCase on the entry? You need to call key or value on it first.

boreal tusk
#

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

vagrant star
#

and it's not like it is difficult to do it yourself

boreal tusk
#

what is an ide

vagrant star
#

just replace var by the type it is supposed to use

shrewd galleon
#

Integrated Development Environment.

quartz tokenBOT
boreal tusk
#

Is the type supposed to be an int? Since it is an ID right

vagrant star
#

mouse over it

boreal tusk
#

What does that mean? If I try to hover over it but nothing happen

#

even if i hold ctrl like simon said

distant kernel
#

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)) {
        ...
    }
}
boreal tusk
#

Alright I was multitasking for a moment so i couldnt properly pay attention

shrewd galleon
boreal tusk
#

i don't know which program you are using but BlueJ does not have that

shrewd galleon
#

I'm using IntelliJ.

#

The community edition is free to use.

boreal tusk
#

I see, I'll use that for non class related coding then

#

This is unfortunately what my class uses

vagrant star
boreal tusk
#

This is what a normal method looks like inside blueJ

#

I tried control cllicking but nothing happened

boreal tusk
#

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

shrewd galleon
#

You can call methods on an entry.

#

Like I said you can ask the key and value of an entry.

boreal tusk
#

So would I need to implement something that gets the key and value from the entry, then call it on that?

shrewd galleon
#

You really should take a look at the methods of what you're using.

boreal tusk
#

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

shrewd galleon
#

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?

boreal tusk
#

Most likely the getKey? Then I can get the key and call the equalsignorescase on that

shrewd galleon
#

The getKey method already returns the key.

#

And what will the data type of your key be?

boreal tusk
#

Assuming the key is an Id, int? If it's not that, a string

shrewd galleon
#

How would you be able the know what type your key and value are respectively?

boreal tusk
#

using the getKey and getValue returns them

shrewd galleon
#

No, how would you be able to know the data type of your key and value respectively?

boreal tusk
#

Perhaps the same as the hashmap?

shrewd galleon
#

What does an entry represent?

boreal tusk
#

In this case, an employee i think, so that should be called an Element correct?

shrewd galleon
#

No.

#

We called entrySet() on your map, so an entry represents one entry of your hashmap.

#

Thus you key and value are that respectively.

boreal tusk
#

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?

shrewd galleon
#

It's all.

#

After all you call entrySet() on your map.

boreal tusk
#

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

shrewd galleon
#

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.

boreal tusk
#

So in this case, both are string

#

since employees is HashMap<String, String>

shrewd galleon
#

It's just following the flow of your logic.

boreal tusk
#

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())