如何在Java中使用SortedMap接口或TreeMap?

发布于 2024-12-04 10:59:36 字数 268 浏览 2 评论 0原文

我有一个

 Map<Float, MyObject>

根据浮动对地图进行排序的最佳方法是什么?

SortedMapTreeMap 是最好的答案吗?
我该如何使用它?

我只创建一次地图,并经常使用 myMap.put()myMap.get() 替换 MyObject

I have a

 Map<Float, MyObject>

What is the best way to keep the map sorted according to the float?

Is SortedMap or TreeMap the best answer?
How do I use it?

I only create the map once and replace the MyObject frequently using myMap.put() and myMap.get().

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

音栖息无 2024-12-11 10:59:36

我会使用TreeMap,它实现SortedMap。它正是为此而设计的。

示例:

Map<Integer, String> map = new TreeMap<Integer, String>();

// Add Items to the TreeMap
map.put(1, "One");
map.put(2, "Two");
map.put(3, "Three");

// Iterate over them
for (Map.Entry<Integer, String> entry : map.entrySet()) {
    System.out.println(entry.getKey() + " => " + entry.getValue());
}

请参阅SortedMap 的 Java 教程页面。< br>
这里有与 TreeMap 相关的教程列表

I would use TreeMap, which implements SortedMap. It is designed exactly for that.

Example:

Map<Integer, String> map = new TreeMap<Integer, String>();

// Add Items to the TreeMap
map.put(1, "One");
map.put(2, "Two");
map.put(3, "Three");

// Iterate over them
for (Map.Entry<Integer, String> entry : map.entrySet()) {
    System.out.println(entry.getKey() + " => " + entry.getValue());
}

See the Java tutorial page for SortedMap.
And here a list of tutorials related to TreeMap.

很糊涂小朋友 2024-12-11 10:59:36

TreeMap 可能是最直接的方法。您可以像使用普通地图一样使用它。即

Map<Float,String> mySortedMap = new TreeMap<Float,MyObject>();
// Put some values in it
mySortedMap.put(1.0f,"One");
mySortedMap.put(0.0f,"Zero");
mySortedMap.put(3.0f,"Three");

// Iterate through it and it'll be in order!
for(Map.Entry<Float,String> entry : mySortedMap.entrySet()) {
    System.out.println(entry.getValue());
} // outputs Zero One Three 

值得一看 API 文档, http: //download.oracle.com/javase/6/docs/api/java/util/TreeMap.html 看看您还可以用它做什么。

A TreeMap is probably the most straightforward way of doing this. You use it exactly like a normal Map. i.e.

Map<Float,String> mySortedMap = new TreeMap<Float,MyObject>();
// Put some values in it
mySortedMap.put(1.0f,"One");
mySortedMap.put(0.0f,"Zero");
mySortedMap.put(3.0f,"Three");

// Iterate through it and it'll be in order!
for(Map.Entry<Float,String> entry : mySortedMap.entrySet()) {
    System.out.println(entry.getValue());
} // outputs Zero One Three 

It's worth taking a look at the API docs, http://download.oracle.com/javase/6/docs/api/java/util/TreeMap.html to see what else you can do with it.

动听の歌 2024-12-11 10:59:36

您可以使用 TreeMap,它在内部实现 SortedMap,下面是示例

按升序排序:

  Map<Float, String> ascsortedMAP = new TreeMap<Float, String>();

  ascsortedMAP.put(8f, "name8");
  ascsortedMAP.put(5f, "name5");
  ascsortedMAP.put(15f, "name15");
  ascsortedMAP.put(35f, "name35");
  ascsortedMAP.put(44f, "name44");
  ascsortedMAP.put(7f, "name7");
  ascsortedMAP.put(6f, "name6");

  for (Entry<Float, String> mapData : ascsortedMAP.entrySet()) {
    System.out.println("Key : " + mapData.getKey() + "Value : " + mapData.getValue());
  }

按降序排序:

如果您始终希望创建地图以使用降序排列一般来说,如果您只需要一次,请创建一个降序排列的 TreeMap 并将原始映射中的所有数据放入其中。

  // Create the map and provide the comparator as a argument
  Map<Float, String> dscsortedMAP = new TreeMap<Float, String>(new Comparator<Float>() {
    @Override
    public int compare(Float o1, Float o2) {
      return o2.compareTo(o1);
    }
  });
  dscsortedMAP.putAll(ascsortedMAP);

有关 SortedMAP 的更多信息,请阅读 http://examples.javacodegeeks.com/core-java/ util/treemap/java-sorted-map-example/

You can use TreeMap which internally implements the SortedMap below is the example

Sorting by ascending ordering :

  Map<Float, String> ascsortedMAP = new TreeMap<Float, String>();

  ascsortedMAP.put(8f, "name8");
  ascsortedMAP.put(5f, "name5");
  ascsortedMAP.put(15f, "name15");
  ascsortedMAP.put(35f, "name35");
  ascsortedMAP.put(44f, "name44");
  ascsortedMAP.put(7f, "name7");
  ascsortedMAP.put(6f, "name6");

  for (Entry<Float, String> mapData : ascsortedMAP.entrySet()) {
    System.out.println("Key : " + mapData.getKey() + "Value : " + mapData.getValue());
  }

Sorting by descending ordering :

If you always want this create the map to use descending order in general, if you only need it once create a TreeMap with descending order and put all the data from the original map in.

  // Create the map and provide the comparator as a argument
  Map<Float, String> dscsortedMAP = new TreeMap<Float, String>(new Comparator<Float>() {
    @Override
    public int compare(Float o1, Float o2) {
      return o2.compareTo(o1);
    }
  });
  dscsortedMAP.putAll(ascsortedMAP);

for further information about SortedMAP read http://examples.javacodegeeks.com/core-java/util/treemap/java-sorted-map-example/

孤独患者 2024-12-11 10:59:36

TreeMap(它是 SortedMap 接口的实现)可以工作。

我该如何使用它?

Map<Float, MyObject> map = new TreeMap<Float, MyObject>();

TreeMap, which is an implementation of the SortedMap interface, would work.

How do I use it ?

Map<Float, MyObject> map = new TreeMap<Float, MyObject>();
陌伤ぢ 2024-12-11 10:59:36

tl;dr

使用 Map 与 Java 6 及更高版本捆绑在一起的实现 NavigableMapSortedMap):

  • 使用 TreeMap 如果运行单线程,或者如果映射在第一个之后跨线程只读正在有人居住。
  • 使用 < code>ConcurrentSkipListMap 如果跨线程操作映射。

NavigableMap

仅供参考,SortedMap 接口由 NavigableMap接口。

如果使用尚未声明支持 NavigableMap 的第 3 方实现,则只需使用 SortedMap。在与 Java 捆绑的地图中,两个实现 SortedMap 的实现也实现 NavigableMap

接口与具体类

SortedMap 是最佳答案吗?树形图?

,而 TreeMap 是该接口的多个实现之一(以及更新的 NavigableMap)。

正如其他人提到的,SortedMap 是一个接口 如果您以后决定在实现之间切换,则可以编写使用该映射的代码,

NavigableMap< Employee , Project > currentAssignments = new TreeSet<>() ;
currentAssignments.put( alice , writeAdCopyProject ) ; 
currentAssignments.put( bob , setUpNewVendorsProject ) ; 

如果以后更改实现,则该代码仍然有效。 将该声明更改为:

NavigableMap< Employee , Project > currentAssignments = new ConcurrentSkipListMap<>() ;

...和。使用该映射的其余代码继续 Java 11 捆绑了十种 Map 实现。

选择实现

还有第三方提供的更多实现,例如 Google Guava

这是我制作的一个图表,突出显示了每个功能的各种功能。请注意,两个捆绑实现通过检查键的内容来保持键的排序顺序。此外, EnumMap 按照该枚举上定义的对象的顺序保留其键。最后,LinkedHashMap 会记住原始插入顺序。

表格Java 11 中的地图实现,比较它们的功能

tl;dr

Use either of the Map implementations bundled with Java 6 and later that implement NavigableMap (the successor to SortedMap):

  • Use TreeMap if running single-threaded, or if the map is to be read-only across threads after first being populated.
  • Use ConcurrentSkipListMap if manipulating the map across threads.

NavigableMap

FYI, the SortedMap interface was succeeded by the NavigableMap interface.

You would only need to use SortedMap if using 3rd-party implementations that have not yet declared their support of NavigableMap. Of the maps bundled with Java, both of the implementations that implement SortedMap also implement NavigableMap.

Interface versus concrete class

s SortedMap the best answer? TreeMap?

As others mentioned, SortedMap is an interface while TreeMap is one of multiple implementations of that interface (and of the more recent NavigableMap.

Having an interface allows you to write code that uses the map without breaking if you later decide to switch between implementations.

NavigableMap< Employee , Project > currentAssignments = new TreeSet<>() ;
currentAssignments.put( alice , writeAdCopyProject ) ; 
currentAssignments.put( bob , setUpNewVendorsProject ) ; 

This code still works if later change implementations. Perhaps you later need a map that supports concurrency for use across threads. Change that declaration to:

NavigableMap< Employee , Project > currentAssignments = new ConcurrentSkipListMap<>() ;

…and the rest of your code using that map continues to work.

Choosing implementation

There are ten implementations of Map bundled with Java 11. And more implementations provided by 3rd parties such as Google Guava.

Here is a graphic table I made highlighting the various features of each. Notice that two of the bundled implementations keep the keys in sorted order by examining the key’s content. Also, EnumMap keeps its keys in the order of the objects defined on that enum. Lastly, the LinkedHashMap remembers original insertion order.

Table of map implementations in Java 11, comparing their features

幸福丶如此 2024-12-11 10:59:36

TreeMap 按键自然顺序排序。这些键应该实现 Comparable 或与 Comparator 兼容(如果您将一个实例传递给构造函数)。在您的情况下,Float 已经实现了Comparable,因此您无需执行任何特殊操作。

您可以调用keySet来按升序检索所有键。

TreeMap sorts by the key natural ordering. The keys should implement Comparable or be compatible with a Comparator (if you passed one instance to constructor). In you case, Float already implements Comparable so you don't have to do anything special.

You can call keySet to retrieve all the keys in ascending order.

你怎么敢 2024-12-11 10:59:36

您可以使用实现 SortedMap 接口的 TreeMap 类来实现此目的。

TreeMap 类实现了 NavigableMap 接口,该接口扩展了 SortedMap 接口。

这将产生以下效果:所有键都将根据其 Comparable 接口的实现进行排序。

Map<Integer, String> map = new TreeMap<>();

// Add Items to the TreeMap
map.put(9999, "foo");
map.put(23432, "bar");
map.put(6, "foobar");
map.put(12, "baz");

键现在会自动按排序顺序排列。当我们迭代它们时,我们得到以下结果:

map.forEach((k, v) -> System.out.println("key: " + k));

// output:
// key: 6
// key: 12
// key: 9999
// key: 23432

因为 TreeMap 元素需要排序,所以用作键的对象需要具有 Comparable 接口的实现。例如,以下代码将引发运行时错误:

class Human{}
Map<Human, String> map = new TreeMap<>();

// Following throws a exception:
// Exception in thread "main" java.lang.ClassCastException:
// class Example$1Human cannot be cast to class java.lang.Comparable 
map.put(new Human(), "baz");

You can use the TreeMap class for this purpose which implements the SortedMap interface.

The class TreeMap implements the NavigableMap interface which extends the SortedMap interface.

This will have the effect that all the keys will be ordered according to their implementation of their Comparable interface.

Map<Integer, String> map = new TreeMap<>();

// Add Items to the TreeMap
map.put(9999, "foo");
map.put(23432, "bar");
map.put(6, "foobar");
map.put(12, "baz");

The keys are now automatically in sorted order. When we iterate over them we get the following:

map.forEach((k, v) -> System.out.println("key: " + k));

// output:
// key: 6
// key: 12
// key: 9999
// key: 23432

Because TreeMap elements are required to be ordered the Objects which are used as a key need to have a implementation of the Comparable interface. For example the following code will throw a runtime error:

class Human{}
Map<Human, String> map = new TreeMap<>();

// Following throws a exception:
// Exception in thread "main" java.lang.ClassCastException:
// class Example$1Human cannot be cast to class java.lang.Comparable 
map.put(new Human(), "baz");
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文