0

i would like if someone can check out this piece of code, the code should transform an array into a list and then into a map. The key should have the value of the list element and the value should be True if it's an even number and False if it's odd. The array is "8, 6, 1, 5, 3, 9, 2". I'm pretty sure this is the right way but when printing the map i get a lot of lines, it's my first time doing with maps so i'm not sure if that's the way it should be or i messed something up huh. Code:

    static public void toMap(int x[]) {
    List<Integer> list = new ArrayList<>();
    Map<Integer, String> map = new HashMap<>();
    for (int t : x) { 
        list.add(t); 
    }
        
    for(int z : list) {
        String tf;
        if(z % 2 == 0)
            tf = "True";
        else 
            tf = "False";
        map.put(z,tf);
        
        for (Map.Entry<Integer, String> mp : map.entrySet()) {
            System.out.println(mp.getKey() + "/" + mp.getValue());
        }
    }
}

Getting this when printing:

enter image description here

Any help/tip would be appreciated, thanks in advance!

2
  • 1
    You could do this a lot more concisely by using java 8 streams. Commented Jul 6, 2020 at 18:10
  • 1
    your identation is wrong. The foreach on the map entries should be out of the foreach of the loop Commented Jul 6, 2020 at 18:11

6 Answers 6

2

You are printing inside the for loop and that is causing the issue. You need to move it outside the for loop. Here is the updated code -

    static public void toMap(int[] x) {
        List<Integer> list = new ArrayList<>();
        for (int t : x) {
            list.add(t);
        }

        Map<Integer, String> map = new HashMap<>();
        for(int z : list) {
            String tf;
            if(z % 2 == 0)
                tf = "True";
            else
                tf = "False";
            map.put(z,tf);
        }

        for (Map.Entry<Integer, String> mp : map.entrySet()) {
            System.out.println(mp.getKey() + "/" + mp.getValue());
        }
    }

Also you can simplify it a bit as below -

    public static void main(String[] args) {
        Integer[] array = {8, 6, 1, 5, 3, 9, 2};
        toMap(array);
    }

    static public void toMap(Integer[] x) {
        List<Integer> list = Arrays.asList(x);
        Map<Integer, String> map = new HashMap<>();
        list.forEach(i -> {
            if (i % 2 == 0)
                map.put(i, "True");
            else
                map.put(i, "False");
        });
        System.out.println(map);
    }
Sign up to request clarification or add additional context in comments.

Comments

1

You are putting the loop for printing out the map inside the loop that creates it, so every time you add an entry it reprints the map. You actually do have the correct map -- the last few lines of output.

To fix it you should move that last for loop out to make it

for(int z : list) {
        String tf;
        if(z % 2 == 0)
            tf = "True";
        else 
            tf = "False";
        map.put(z,tf);
        
    }
for (Map.Entry<Integer, String> mp : map.entrySet()) {
            System.out.println(mp.getKey() + "/" + mp.getValue());
        }

Comments

1

This is a clear example of why you should always put the braces in your code, you get lost.

for(int z : list) {
    String tf;
    if(z % 2 == 0) {
        tf = "True";
    }
    else {
        tf = "False";
    }
    map.put(z,tf);
    
    for (Map.Entry<Integer, String> mp : map.entrySet()) {
        System.out.println(mp.getKey() + "/" + mp.getValue());
    }
}

If we put the braces there, you can clearly see that you have the printing for-loop inside the other one. This is harder to see without the braces.

Move that printing loop outside the other one and you should be good.

Comments

0

You need to move the printing loop outside of the first loop.

Also, a few observations.

  • X == Y returns true or false depending on the value. And booleans will print out as true or false. So why not do the following:
 for(int z : list) {  // you can also replace list with your array here
     map.put(z,z % 2 == 0);
 }
  // or if you want Strings
 for (int z : list) {
    map.put(z, z % 2 == 0 ? "True":"False");
 }
 
  • To print them, you can do this.
map.forEach((k,v)->System.out.println(k + "/" + v));

Comments

0

You don't need to iterate twice over the array. Iterate only once, add it to list and even or odd to map.

static public void toMap(int x[]) {
    // List which contains all elements of x.
    List<Integer> list = new ArrayList<>();

    // Map to store element as key and even or not as value
    Map<Integer, Boolean> map = new HashMap<>();

    for (int value: x) {
        list.add(value);
        map.put(value, value % 2 == 0);
    }


    // Printing the map
    for (Map.Entry<Integer, Boolean> m : map.entrySet()) {
        System.out.println(m.getKey() + "," + m.getValue());
    }
}

Comments

0

As others have said, your problem is in the nesting. You are looping through all of your map entries for every integer in the input array. That said, I think the bigger issue is you have over-complicated your method. Using a few tricks, you can simplify your code down to something like this:

public static void toMap(int[] x) {
    HashMap<Integer, String> map = new HashMap<>();
    ArrayList<Integer> list = new ArrayList<>();

    for (int i : x) {
        map.put(i, (i & 1) == 0 ? "True" : "False"); //puts "True" if i is even, else "False"
    }

    list.addAll(map.keySet()); //adds all the map's keys to the ArrayList
    map.forEach((k, v) -> System.out.printf("%d/%s%n", k, v)); //prints out all the entries formatted as you specified
}

Or, if you don't actually need the ArrayList for anything specific, you can just get rid of it:

public static void toMap(int[] x) {
    HashMap<Integer, String> map = new HashMap<>();

    for (int i : x) {
        map.put(i, (i & 1) == 0 ? "True" : "False"); //puts "True" if i is even, else "False"
    }

    map.forEach((k, v) -> System.out.printf("%d/%s%n", k, v)); //prints out all the entries formatted as you specified
}

Or, if you don't actually need any of the functions of the map, you can just get rid of that, too. Just print straight from the for loop, like so:

public static void toMap(int[] x) {
    for (int i : x) {
        System.out.printf("%d/%s%n", i, (i & 1) == 0 ? "True" : "False");
    }
}

Or, if you don't mind the true/false being all lowercase, you can let Java do the string conversion for you:

public static void toMap(int[] x) {
    for (int i : x) {
        System.out.printf("%d/%s%n", i, (i & 1) == 0);
    }
}

Finally, if you're into one-liners, and don't mind it being a bit messy, you can do it all in one line:

public static void toMap(int[] x) {
    IntStream.of(x).forEach((i) -> System.out.printf("%d/%s%n", i, (i & 1) == 0));
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.