Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Java Quiz: Using TreeMap in Java

DZone's Guide to

Java Quiz: Using TreeMap in Java

The latest advanced Java quiz from DZone's resident quizmaster! This week: How TreeMap determines the output of strings of text in Java.

· Java Zone
Free Resource

Learn how to stop testing everything every sprint and only test the code you’ve changed. Brought to you by Parasoft.

Last Week's Answer

Many programmers might try to find the value of x by passing all the array elements to the switch statement, but that is unnecessary.

In this quiz you don't need to calculate the return value of methodB, but you can pass the value, which is x/2 to the methodB first arg. You can find the result by calculating the following simple mathematical formulas.

int methodB(x/2, 2)

int i3 = i + i2 - 1;
i3 = x/2 + 1;
return(i3 - (2 * i) / x - x / 2); = x/2 +1 – (2x/2)/x – x/2
= 1- x/x = 1-1 = 0

The correct answer is e = 0.

This Week's Quiz

Purpose

  1. Demonstrating how TreeMap behaves

  2. Brain training to improve your imagination

What is written to the standard output as the result of executing the following code?

import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeMap;

public class MyClass{

    private TreeMap<String,Integer> studentMap = new TreeMap<String,Integer>();

    public void getStudents(){
        studentMap.put("Lola",new Integer(8));
        studentMap.put("Alexa",new Integer(5));
        studentMap.put("Mason",new Integer(8));
        studentMap.put("Michael",new Integer(6));
        studentMap.put("Gemma",new Integer(8));
        studentMap.put("Alexa",new Integer(6));
        studentMap.put("Lola",new Integer(4));
        studentMap.put("Michael",new Integer(5));
        studentMap.put("Alexa",new Integer(8));

        Set<Entry<String,Integer>> set = studentMap.entrySet();
        Iterator iter = set.iterator();
        while(iter.hasNext()){
            Map.Entry entry = (Map.Entry)iter.next();
            Integer i = (Integer)entry.getValue();
            if(i > 5){
                System.out.print(entry.getKey() + " ");
            }
        }
    }
    public static void main(String[] args){
        MyClass mc = new MyClass();
        mc.getStudents();
    }
}


Let us know your thoughts in the comments, and check out Sar's site here!

Get the top tips for Java developers and best practices to overcome common challenges. Brought to you by Parasoft.

Topics:
java ,treemap ,quiz

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}