Results 1 to 13 of 13
Like Tree1Likes
  • 1 Post By jim829

Thread: map with duplicates - sort by value (duplicates disappear, but I need them)

  1. #1
    marchello is offline Member
    Join Date
    Apr 2013
    Posts
    15
    Rep Power
    0

    Question map with duplicates - sort by value (duplicates disappear, but I need them)

    Hi all,
    I got map with full duplicates (key and value are duplicated). I need to sort the map by value, it sorts, but duplicates disappear and I need to keep them. Please see my code below.

    Java Code:
    package learn;
     
    import java.util.IdentityHashMap;
    import java.util.LinkedHashMap;
    import java.util.LinkedList;
    import java.util.List;
    import java.util.Map;
    import java.util.Map.Entry;
    import java.util.stream.Collectors;
     
    public class sortMapWithDuplicates {
     
        private static Map<Integer, String> sortByValue(Map<Integer, String> unsortMap, final boolean order)
        {
            List<Entry<Integer, String>> list = new LinkedList<>(unsortMap.entrySet());
            System.out.println("check 1 - list = " + list);
            list.sort((o1, o2) -> order ? o1.getValue().compareTo(o2.getValue()) == 0
                    ? o1.getKey().compareTo(o2.getKey())
                    : o1.getValue().compareTo(o2.getValue()) : o2.getValue().compareTo(o1.getValue()) == 0
                    ? o2.getKey().compareTo(o1.getKey())
                    : o2.getValue().compareTo(o1.getValue()));
            System.out.println("check 2 - list sorted before return = " + list);
            return list.stream().collect(Collectors.toMap(Entry::getKey, Entry::getValue, (a, b) -> b, LinkedHashMap::new));
        }
     
    	  public static void main(String[] args) {
    		  Map<Integer, String> map = new IdentityHashMap<Integer, String>();
    		  map.put(new Integer(1), "one");
    		  map.put(new Integer(1), "one");
    		  map.put(new Integer(2), "two");
    		  map.put(new Integer(3), "three");
    		  map.put(new Integer(4), "four");
    		  System.out.println(sortByValue(map,true));
    	  }
     
    }
    Console output:
    check 1 - list = [1=one, 3=three, 2=two, 1=one, 4=four]
    check 2 - list sorted before return = [4=four, 1=one, 1=one, 3=three, 2=two]
    {4=four, 1=one, 3=three, 2=two}
    As you can see, my two check steps show that duplicates are present, but they disappear on return.
    Thx for any suggestion.

  2. #2
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    19,960
    Rep Power
    31

    Default Re: map with duplicates - sort by value (duplicates disappear, but I need them)

    An interesting demonstration of an inconsistancy in java's treatment of Integers. You'd expect there to be duplicate keys for the two uses of new Integer(1). A Map can not have duplicate keys.
    If the code used small int values that would be autoboxed, then the keys would be duplicates.
    Java Code:
              System.out.println(map.put(99, "nines 1"));
              System.out.println(map.put(99, "nines 2"));                   // nine 1
    Also posted at: http://www.javaprogrammingforums.com...tml#post162989
    Last edited by Norm; 08-28-2018 at 02:32 PM.
    If you don't understand my response, don't ignore it, ask a question.

  3. #3
    marchello is offline Member
    Join Date
    Apr 2013
    Posts
    15
    Rep Power
    0

    Default Re: map with duplicates - sort by value (duplicates disappear, but I need them)

    Quote Originally Posted by Norm View Post
    An interesting demonstration of an inconsistancy in java's treatment of Integers. You'd expect there to be duplicate keys for the two uses of new Integer(1). A Map can not have duplicate keys.
    If the code used small int values that would be autoboxed, then the keys would be duplicates.
    Java Code:
              System.out.println(map.put(99, "nines 1"));
              System.out.println(map.put(99, "nines 2"));                   // nine 1
    Norm, thank you for your reply!
    So it is just not intended to keep duplicates and my workaround with new Integers(1) was a kind of hack that should not exist... If I understand you right...
    Any other way to store pair of values (int and String) with duplicates and then sort by String value instead of map?
    Please advise.

  4. #4
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    19,960
    Rep Power
    31

    Default Re: map with duplicates - sort by value (duplicates disappear, but I need them)

    with duplicates
    A Map should not allow duplicate keys. Java's autoboxing and caching of values makes it hard to program like you want.
    If you don't understand my response, don't ignore it, ask a question.

  5. #5
    marchello is offline Member
    Join Date
    Apr 2013
    Posts
    15
    Rep Power
    0

    Default Re: map with duplicates - sort by value (duplicates disappear, but I need them)

    Quote Originally Posted by Norm View Post
    A Map should not allow duplicate keys. Java's autoboxing and caching of values makes it hard to program like you want.
    Is there any other way to do this? I can insert data into any database like mysql and then sort values by String column. This is what I would do in my local environment. The problem is that it is online tutorial for java learning purpose where I can not use any databases. So.. any other solution except using db? Please advise.

  6. #6
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    19,960
    Rep Power
    31

    Default Re: map with duplicates - sort by value (duplicates disappear, but I need them)

    What is the purpose of using a Map if ordinary Maps don't allow duplicate keys? Why not just a List?
    The IdentityHashMap has different rules on keys (uses reference vs value equality). See the API doc for a discussion.
    If you don't understand my response, don't ignore it, ask a question.

  7. #7
    marchello is offline Member
    Join Date
    Apr 2013
    Posts
    15
    Rep Power
    0

    Default Re: map with duplicates - sort by value (duplicates disappear, but I need them)

    Quote Originally Posted by Norm View Post
    What is the purpose of using a Map if ordinary Maps don't allow duplicate keys? Why not just a List?
    The IdentityHashMap has different rules on keys (uses reference vs value equality). See the API doc for a discussion.
    Using a Map was just because of my knowledge level (entry level tbh). I would use any other way, including a List. If you got some simple example, it would be great. I'll investigate this, thx.

  8. #8
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    6,222
    Rep Power
    12

    Default Re: map with duplicates - sort by value (duplicates disappear, but I need them)

    Interesting problem but I don't see how a map would work in this case. If duplicates were allowed and then you requested the value for the key new Integer(1), how would the map know which value you were interested in? Also, you have explained the coding dilemma but I don't see any explanation of what you want to accomplish or why you want to retain duplicates. So it is not possible to provide an alternate solution, imho.

    Having said that, if you want to have multiple values for the same key, then you could have a map of lists.

    Map<Integer, List<Integer>>

    That way you can retrieve a list of values for a given key. But that complicates sorting the map based on values.

    Regards,
    Jim
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  9. #9
    marchello is offline Member
    Join Date
    Apr 2013
    Posts
    15
    Rep Power
    0

    Default Re: map with duplicates - sort by value (duplicates disappear, but I need them)

    Jim, thank you for your reply!
    Quote Originally Posted by jim829 View Post
    why you want to retain duplicates
    This is because the task is tricky and it requires code to deal with duplicates...

  10. #10
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    6,222
    Rep Power
    12

    Default Re: map with duplicates - sort by value (duplicates disappear, but I need them)

    That still doesn't tell anyone anything. Why do you need to retain duplicates? How will the map be used in the application you are writing.

    Your "task," for example is not to throw sand on the fire, but to put out the fire. Using sand is just one option.

    Regards,
    Jim
    SurfMan likes this.
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  11. #11
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    6,222
    Rep Power
    12

    Default Re: map with duplicates - sort by value (duplicates disappear, but I need them)

    Also posted at https://coderanch.com/t/698312

    Regards,
    Jim
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  12. #12
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    6,222
    Rep Power
    12

    Default Re: map with duplicates - sort by value (duplicates disappear, but I need them)

    I just tried to run your code (I am running Eclipse with Java 10). And the new Integer() constructor has been deprecated since Java 9. If you change those constructs to Integer.valueOf() then duplicates are handled properly (i.e. they are overwritten with the new values).

    EDIT. Well, I just looked at the API and only values in the byte range -128 to 127 are cached. Larger values produce earlier results.

    Regards,
    Jim
    Last edited by jim829; 08-28-2018 at 06:00 PM.
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  13. #13
    marchello is offline Member
    Join Date
    Apr 2013
    Posts
    15
    Rep Power
    0

    Default Re: map with duplicates - sort by value (duplicates disappear, but I need them)

    Hi all,
    Thanks for each of your input.
    Honestly, I feel this task is too difficult for me right now, so I will return to it later.
    Last edited by marchello; 09-04-2018 at 06:21 PM.

Similar Threads

  1. How to compare duplicates in a map
    By jepoys1 in forum New To Java
    Replies: 3
    Last Post: 04-24-2017, 01:29 PM
  2. Replace duplicates
    By dibs in forum New To Java
    Replies: 3
    Last Post: 12-08-2015, 09:57 PM
  3. Removing Duplicates.
    By dashwall in forum New To Java
    Replies: 9
    Last Post: 12-29-2009, 02:03 PM
  4. Duplicates
    By Gambit17 in forum New To Java
    Replies: 5
    Last Post: 11-08-2007, 10:56 AM
  5. duplicates in iReport
    By Heather in forum Advanced Java
    Replies: 1
    Last Post: 07-05-2007, 05:42 AM

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •