HashMap<String, MyClass> map = new HashMap<>();
// ...
List<Map.Entry<String, MyClass>> list = new ArrayList<>(map.entrySet());
list.sort((o1, o2) -> {
String f1 = o1.getValue().field;
String f2 = o2.getValue().field;
// compareResult = ...
return compareResult;
});
The map is sorted according to the natural ordering of its keys, or by a Comparator provided at map creation time, depending on which constructor is used.
Note that this implementation is not synchronized. If multiple threads access a map concurrently, and at least one of the threads modifies the map structurally, it must be synchronized externally. (A structural modification is any operation that adds or deletes one or more mappings; merely changing the value associated with an existing key is not a structural modification.) This is typically accomplished by synchronizing on some object that naturally encapsulates the map. If no such object exists, the map should be "wrapped" using the Collections.synchronizedSortedMap method. This is best done at creation time, to prevent accidental unsynchronized access to the map:
SortedMap m = Collections.synchronizedSortedMap(new TreeMap(...));
The iterators returned by the iterator method of the collections returned by all of this class's "collection view methods" are fail-fast: if the map is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove method, the iterator will throw a ConcurrentModificationException. Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future.
HashMap<String,SomeClass> someHashMap= ...;
Collections.sort(someHashMap, new Comparator<SomeClass>() {
public int compare(SomeClass o1, SomeClass o2) {
//return a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second.
}
});
точно знаю как изнутри устроен HashMap. Коллизии возникают.тогда вы должны знать что при одинаковом key(коллизия возникла) просто заменится value. Вот с ситуацией если key не имеет собственную реализацию hash и compare то беда точно придет и результат может оказаться непредсказуемым.
List<Map.Entry<String, SomeClass>> comparingByKey = map.entrySet().stream()
.sorted(Map.Entry.comparingByKey((String s1, String s2) -> s1.length() - s2.length())) //Ну или по Value
.collect(Collectors.toList());