Solved

HashMap Vs TreeMap

Posted on 2016-10-04
12
91 Views
Last Modified: 2016-10-05
Hi,

package test;

import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

public class WordCount {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		// wordCount(["a", "b", "a", "c", "b"]) → {"b": 2, "c": 1, "a": 2}
		// Map<String, String> map = new HashMap();
		// map.put("b", null);
		// map.put("a", "Hi");
		String[] arr = { "a","e","b", "a", "c", "b" };
		System.out.println("--->" + wordCount(arr));

	}

	/*
	 * private static String mapAB(String[] arr) { // TODO Auto-generated method
	 * stub return null; }
	 */

	public static Map<String, Integer> wordCount(String[] strings) {
		Map<String, Integer> map = new HashMap();
		for (int i = 0; i < strings.length; i++) {
			String test = strings[i];
			if (map.containsKey(test)) {
				int count = map.get(test);
				map.put(test, count + 1);
			}

			else {
				map.put(test, 1);
			}
		}
		return map;
	}

}

Open in new window

Above gave below output with HashMap
--->{a=2, b=2, c=1, e=1}


package test;

import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

public class WordCount {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		// wordCount(["a", "b", "a", "c", "b"]) → {"b": 2, "c": 1, "a": 2}
		// Map<String, String> map = new HashMap();
		// map.put("b", null);
		// map.put("a", "Hi");
		String[] arr = { "a","e","b", "a", "c", "b" };
		System.out.println("--->" + wordCount(arr));

	}

	/*
	 * private static String mapAB(String[] arr) { // TODO Auto-generated method
	 * stub return null; }
	 */

	public static Map<String, Integer> wordCount(String[] strings) {
		Map<String, Integer> map = new TreeMap();
		for (int i = 0; i < strings.length; i++) {
			String test = strings[i];
			if (map.containsKey(test)) {
				int count = map.get(test);
				map.put(test, count + 1);
			}

			else {
				map.put(test, 1);
			}
		}
		return map;
	}

}

Open in new window


above with TreeMap also gave same output with sorting of key in alphabetical increasing order.

--->{a=2, b=2, c=1, e=1}


What is diffence between HashMap and TreeMap.
Which one should be used in which case? what are advantages and disadvantages of each

please advise
0
Comment
Question by:gudii9
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 6
  • 5
12 Comments
 
LVL 14

Accepted Solution

by:
CPColin earned 250 total points
ID: 41828798
Short answer: Use TreeMap when you need the elements to be sorted. Use HashMap when you don't.

When using TreeMap, either the keys need to implement Comparable or you need to pass an instance of Comparator when you create the map. When using HashMap, the keys should implement both Object.equals() and Object.hashCode().
0
 
LVL 7

Author Comment

by:gudii9
ID: 41828810
Why hashmap sorts here?
0
 
LVL 7

Author Comment

by:gudii9
ID: 41828812
Also tree map without comparator sorts here?
0
Use Filtering Commands to Process Files in Linux

Learn how to manipulate data with the help of various filtering commands such as `cat`, `fmt`, `pr`, and others in Linux.

 
LVL 14

Expert Comment

by:CPColin
ID: 41828813
For HashMap, it's probably a coincidence. Try using other values. For TreeMap, the String class implements Comparable, so you don't need to pass a Comparator.
0
 
LVL 37

Assisted Solution

by:zzynx
zzynx earned 250 total points
ID: 41829425
Why hashmap sorts here?
HashMap does NOT sort.
But sometimes it is possible that HashMap's random order of the keys equals the sorted order.
However, you can't for sure not count on that.
0
 
LVL 7

Author Comment

by:gudii9
ID: 41830646

But sometimes it is possible that HashMap's random order of the keys equals the sorted order.
any specific sometimes order of kesy equal to sorted order?
0
 
LVL 14

Expert Comment

by:CPColin
ID: 41830648
No. It's random. Don't read into it.
0
 
LVL 7

Author Comment

by:gudii9
ID: 41830655
0
 
LVL 7

Author Comment

by:gudii9
ID: 41830668
Apart from String who else implements comparable? is it StringBuffer or StringBuilder I forgot?
0
 
LVL 14

Expert Comment

by:CPColin
ID: 41830677
The Javadocs for Comparable have a huge list.
0
 
LVL 7

Author Comment

by:gudii9
ID: 41830683
All Known Subinterfaces:
ChronoLocalDate, ChronoLocalDateTime<D>, Chronology, ChronoZonedDateTime<D>, Delayed, Name, Path, RunnableScheduledFuture<V>, ScheduledFuture<V>
All Known Implementing Classes:
AbstractChronology, AbstractRegionPainter.PaintContext.CacheMode, AccessMode, AclEntryFlag, AclEntryPermission, AclEntryType, AddressingFeature.Responses, Authenticator.RequestorType, BigDecimal, BigInteger, Boolean, Byte, ByteBuffer, Calendar, CertPathValidatorException.BasicReason, Character, Character.UnicodeScript, CharBuffer, Charset, ChronoField, ChronoUnit, ClientInfoStatus, CollationKey, Collector.Characteristics, Component.BaselineResizeBehavior, CompositeName, CompoundName, CRLReason, CryptoPrimitive, Date, Date, DayOfWeek, Desktop.Action, Diagnostic.Kind, Dialog.ModalExclusionType, Dialog.ModalityType, DocumentationTool.Location, Double, DoubleBuffer, DropMode, Duration, ElementKind, ElementType, Enum, File, FileTime, FileVisitOption, FileVisitResult, Float, FloatBuffer, FormatStyle, Formatter.BigDecimalLayoutForm, FormSubmitEvent.MethodType, GraphicsDevice.WindowTranslucency, GregorianCalendar, GroupLayout.Alignment, HijrahChronology, HijrahDate, HijrahEra, Instant, IntBuffer, Integer, IsoChronology, IsoEra, JapaneseChronology, JapaneseDate, JavaFileObject.Kind, JDBCType, JTable.PrintMode, KeyRep.Type, LayoutStyle.ComponentPlacement, LdapName, LinkOption, LocalDate, LocalDateTime, Locale.Category, Locale.FilteringMode, LocalTime, Long, LongBuffer, MappedByteBuffer, MemoryType, MessageContext.Scope, MinguoChronology, MinguoDate, MinguoEra, Modifier, Month, MonthDay, MultipleGradientPaint.ColorSpaceType, MultipleGradientPaint.CycleMethod, NestingKind, Normalizer.Form, NumericShaper.Range, ObjectName, ObjectStreamField, OffsetDateTime, OffsetTime, PKIXReason, PKIXRevocationChecker.Option, PosixFilePermission, ProcessBuilder.Redirect.Type, Proxy.Type, PseudoColumnUsage, Rdn, ResolverStyle, Resource.AuthenticationType, RetentionPolicy, RoundingMode, RowFilter.ComparisonType, RowIdLifetime, RowSorterEvent.Type, Service.Mode, Short, ShortBuffer, SignStyle, SOAPBinding.ParameterStyle, SOAPBinding.Style, SOAPBinding.Use, SortOrder, SourceVersion, SSLEngineResult.HandshakeStatus, SSLEngineResult.Status, StandardCopyOption, StandardLocation, StandardOpenOption, StandardProtocolFamily, String, SwingWorker.StateValue, TextStyle, ThaiBuddhistChronology, ThaiBuddhistDate, ThaiBuddhistEra, Thread.State, Time, Timestamp, TimeUnit, TrayIcon.MessageType, TypeKind, URI, UUID, WebParam.Mode, Window.Type, XmlAccessOrder, XmlAccessType, XmlNsForm, Year, YearMonth, ZonedDateTime, ZoneOffset, ZoneOffsetTransition, ZoneOffsetTransitionRule.TimeDefinition

i do not see either StringBuilder or StringBuffer in above huge list?
0
 
LVL 14

Expert Comment

by:CPColin
ID: 41830684
That makes sense; they don't implement Comparable.
0

Featured Post

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction This article is the second of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers the basic installation and configuration of the test automation tools used by…
In this post we will learn how to make Android Gesture Tutorial and give different functionality whenever a user Touch or Scroll android screen.
Viewers learn about the “for” loop and how it works in Java. By comparing it to the while loop learned before, viewers can make the transition easily. You will learn about the formatting of the for loop as we write a program that prints even numbers…
Viewers will learn one way to get user input in Java. Introduce the Scanner object: Declare the variable that stores the user input: An example prompting the user for input: Methods you need to invoke in order to properly get  user input:
Suggested Courses

615 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question