Solved

HashMap Vs TreeMap

Posted on 2016-10-04
12
47 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
  • 6
  • 5
12 Comments
 
LVL 14

Accepted Solution

by:
CPColin earned 250 total points
Comment Utility
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
Comment Utility
Why hashmap sorts here?
0
 
LVL 7

Author Comment

by:gudii9
Comment Utility
Also tree map without comparator sorts here?
0
 
LVL 14

Expert Comment

by:CPColin
Comment Utility
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
Comment Utility
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
Comment Utility

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
How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

 
LVL 14

Expert Comment

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

Author Comment

by:gudii9
Comment Utility
0
 
LVL 7

Author Comment

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

Expert Comment

by:CPColin
Comment Utility
The Javadocs for Comparable have a huge list.
0
 
LVL 7

Author Comment

by:gudii9
Comment Utility
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
Comment Utility
That makes sense; they don't implement Comparable.
0

Featured Post

What Is Threat Intelligence?

Threat intelligence is often discussed, but rarely understood. Starting with a precise definition, along with clear business goals, is essential.

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
copyEndy  challenge 15 55
network + 7 73
array11 challenge 16 50
Image decoding from Camera 3 42
INTRODUCTION Working with files is a moderately common task in Java.  For most projects hard coding the file names, using parameters in configuration files, or using command-line arguments is sufficient.   However, when your application has vi…
In this post we will learn how to connect and configure Android Device (Smartphone etc.) with Android Studio. After that we will run a simple Hello World Program.
Viewers will learn about if statements in Java and their use The if statement: The condition required to create an if statement: Variations of if statements: An example using if statements:
Viewers will learn about basic arrays, how to declare them, and how to use them. Introduction and definition: Declare an array and cover the syntax of declaring them: Initialize every index in the created array: Example/Features of a basic arr…

772 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

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now