Link to home
Start Free TrialLog in
Avatar of gudii9
gudii9Flag for United States of America

asked on

HashMap Vs TreeMap

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
ASKER CERTIFIED SOLUTION
Avatar of CPColin
CPColin
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of gudii9

ASKER

Why hashmap sorts here?
Avatar of gudii9

ASKER

Also tree map without comparator sorts here?
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.
SOLUTION
Avatar of zzynx
zzynx
Flag of Belgium image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of gudii9

ASKER


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?
No. It's random. Don't read into it.
Avatar of gudii9

ASKER

Apart from String who else implements comparable? is it StringBuffer or StringBuilder I forgot?
The Javadocs for Comparable have a huge list.
Avatar of gudii9

ASKER

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?
That makes sense; they don't implement Comparable.