gudii9
asked on
HashMap Vs TreeMap
Hi,
--->{a=2, b=2, c=1, e=1}
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
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;
}
}
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;
}
}
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
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
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
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
any specific sometimes order of kesy equal to sorted order?
But sometimes it is possible that HashMap's random order of the keys equals the sorted order.
No. It's random. Don't read into it.
ASKER
ASKER
Apart from String who else implements comparable? is it StringBuffer or StringBuilder I forgot?
The Javadocs for Comparable have a huge list.
ASKER
All Known Subinterfaces:
ChronoLocalDate, ChronoLocalDateTime<D>, Chronology, ChronoZonedDateTime<D>, Delayed, Name, Path, RunnableScheduledFuture<V>, ScheduledFuture<V>
All Known Implementing Classes:
AbstractChronology, AbstractRegionPainter.PaintContext.C acheMode, AccessMode, AclEntryFlag, AclEntryPermission, AclEntryType, AddressingFeature.Response s, Authenticator.RequestorTyp e, BigDecimal, BigInteger, Boolean, Byte, ByteBuffer, Calendar, CertPathValidatorException .BasicReas on, Character, Character.UnicodeScript, CharBuffer, Charset, ChronoField, ChronoUnit, ClientInfoStatus, CollationKey, Collector.Characteristics, Component.BaselineResizeBe havior, 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.BigDecimalLayout Form, FormSubmitEvent.MethodType , GraphicsDevice.WindowTrans lucency, GregorianCalendar, GroupLayout.Alignment, HijrahChronology, HijrahDate, HijrahEra, Instant, IntBuffer, Integer, IsoChronology, IsoEra, JapaneseChronology, JapaneseDate, JavaFileObject.Kind, JDBCType, JTable.PrintMode, KeyRep.Type, LayoutStyle.ComponentPlace ment, LdapName, LinkOption, LocalDate, LocalDateTime, Locale.Category, Locale.FilteringMode, LocalTime, Long, LongBuffer, MappedByteBuffer, MemoryType, MessageContext.Scope, MinguoChronology, MinguoDate, MinguoEra, Modifier, Month, MonthDay, MultipleGradientPaint.Colo rSpaceType , MultipleGradientPaint.Cycl eMethod, NestingKind, Normalizer.Form, NumericShaper.Range, ObjectName, ObjectStreamField, OffsetDateTime, OffsetTime, PKIXReason, PKIXRevocationChecker.Opti on, PosixFilePermission, ProcessBuilder.Redirect.Ty pe, Proxy.Type, PseudoColumnUsage, Rdn, ResolverStyle, Resource.AuthenticationTyp e, RetentionPolicy, RoundingMode, RowFilter.ComparisonType, RowIdLifetime, RowSorterEvent.Type, Service.Mode, Short, ShortBuffer, SignStyle, SOAPBinding.ParameterStyle , SOAPBinding.Style, SOAPBinding.Use, SortOrder, SourceVersion, SSLEngineResult.HandshakeS tatus, 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.T imeDefinit ion
i do not see either StringBuilder or StringBuffer in above huge list?
That makes sense; they don't implement Comparable.
ASKER