Solved

HashMap Vs TreeMap

Posted on 2016-10-04
12
55 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
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
 
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
DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

 
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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

Suggested Solutions

Java contains several comparison operators (e.g., <, <=, >, >=, ==, !=) that allow you to compare primitive values. However, these operators cannot be used to compare the contents of objects. Interface Comparable is used to allow objects of a cl…
Java had always been an easily readable and understandable language.  Some relatively recent changes in the language seem to be changing this pretty fast, and anyone that had not seen any Java code for the last 5 years will possibly have issues unde…
Viewers learn about the “while” loop and how to utilize it correctly in Java. Additionally, viewers begin exploring how to include conditional statements within a while loop and avoid an endless loop. Define While Loop: Basic Example: Explanatio…
Video by: Michael
Viewers learn about how to reduce the potential repetitiveness of coding in main by developing methods to perform specific tasks for their program. Additionally, objects are introduced for the purpose of learning how to call methods in Java. Define …

863 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

25 Experts available now in Live!

Get 1:1 Help Now