source: josm/trunk/src/org/openstreetmap/josm/data/osm/OsmPrimitiveComparator.java@ 11674

Last change on this file since 11674 was 11177, checked in by simon04, 7 years ago

Refactor OsmPrimitiveComparator

Replace one big comparator with functions to obtain specific simple comparators.

  • Property svn:eol-style set to native
File size: 2.7 KB
Line 
1// License: GPL. For details, see LICENSE file.
2package org.openstreetmap.josm.data.osm;
3
4import static java.util.Comparator.comparing;
5import static java.util.Comparator.comparingInt;
6
7import java.util.Comparator;
8import java.util.HashMap;
9import java.util.Map;
10import java.util.function.Function;
11
12import org.openstreetmap.josm.gui.DefaultNameFormatter;
13import org.openstreetmap.josm.tools.AlphanumComparator;
14
15/**
16 * Comparators for comparing primitives.
17 */
18public final class OsmPrimitiveComparator {
19
20 /**
21 * Returns a comparator comparing primitives by their name using {@link DefaultNameFormatter}.
22 *
23 * {@linkplain DefaultNameFormatter#format(OsmPrimitive) Formatted names} are cached.
24 *
25 * @return a comparator comparing primitives by their name using {@link DefaultNameFormatter}
26 */
27 public static Comparator<OsmPrimitive> comparingNames() {
28 final Comparator<String> digitsLast = comparing(str -> Character.isDigit(str.charAt(0)) ? 1 : 0);
29 return comparing(memoize(DefaultNameFormatter.getInstance()::format),
30 digitsLast.thenComparing(AlphanumComparator.getInstance()));
31 }
32
33 /**
34 * Returns a comparator comparing primitives by their {@linkplain OsmPrimitive#getUniqueId unique id}.
35 *
36 * @return a comparator comparing primitives by their {@linkplain OsmPrimitive#getUniqueId unique id}.
37 */
38 public static Comparator<OsmPrimitive> comparingUniqueId() {
39 return comparing(OsmPrimitive::getUniqueId);
40 }
41
42 /**
43 * Returns a comparator ordering the primitives by type in the order NODE, WAY, RELATION
44 *
45 * @return a comparator ordering the primitives by type in the order NODE, WAY, RELATION
46 */
47 public static Comparator<OsmPrimitive> orderingNodesWaysRelations() {
48 return comparingInt(osm -> osm.getType().ordinal());
49 }
50
51 /**
52 * Returns a comparator ordering the primitives by type in the order WAY, RELATION, NODE
53 *
54 * @return a comparator ordering the primitives by type in the order WAY, RELATION, NODE
55 */
56 public static Comparator<OsmPrimitive> orderingWaysRelationsNodes() {
57 return comparingInt(osm -> {
58 switch (osm.getType()) {
59 case WAY:
60 return 1;
61 case RELATION:
62 return 2;
63 case NODE:
64 return 3;
65 default:
66 throw new IllegalStateException();
67 }
68 });
69 }
70
71 private static <T, R> Function<T, R> memoize(Function<T, R> base) {
72 final Map<T, R> cache = new HashMap<>();
73 return t -> cache.computeIfAbsent(t, base);
74 }
75
76 private OsmPrimitiveComparator() {
77 }
78}
Note: See TracBrowser for help on using the repository browser.