Skip to content

Tag: treemap

Converting List to TreeMap java lambda

I’m trying to convert a List<String> to a TreeMap<Long, CustomClass> The key is the same as the list items but just parsed to Long, the value is just a call to new CustomClass(). How can I achieve this using lambda functions? the above code errors out, with the following error, Answer For ex…

How to match equals() and hashCode in streams?

I have a stream where I am aggregating some data like this: The problem is that by adding this comparator I am braking the contract between hashCode() and equals() and at the end I have duplicate keys: Has anyone some ideas how can I fix this? Or is there a way to sort the final object ( Map<String, Map&lt…

putting value in Treemap understanding issues

I was running through a leetcode problem. and found a solution in the discussion section problem- https://leetcode.com/problems/stock-price-fluctuation/ solution- but I do not understand the following parts. if someone could explain that would be great Answer To solve the problem you need to know how often th…

How to iterate from a given key in Java TreeMap

I have a TreeMap, and want to get a set of K smallest keys (entries) larger than a given value. I know we can use higherKey(givenValue) get the one key, but then how should I iterate from there? One possible way is to get a tailMap from the smallest key larger than the given value, but that’s an overkil…

Comparing the contents of two Treemaps

I have two TreeMaps that I want to compare. I currently have it written down like below but I feel like this could be written more efficiently. I tried looking in to comparators, but I don’t think that’s something I can use for my use-case. The maps are Treemaps because the key must be case-insens…

How to write custom comparator in java?

I want to store key-value pairs in TreeMap and sort the entries based on the value of key as per the following logic: “type” (case insensitive) key should be at first. the key start with “metadata” (case insensitive) should be at last in ascending order rest of the keys(case insensitiv…