Home >Java >javaTutorial >How to use merge in java
The merge() method in Java Collections merges two sorted ordered collections and generates a new sorted collection, maintaining the original order. Syntax: public static
List merge(SortedMap a, SortedMap b). It accepts two sorted collections and returns a new collection containing all elements in sorted order. Note: The values of duplicate keys will be merged according to the merge function, and the original collection will not be modified.
Introduction to the merge() method in Java
The merge() method is used in the Java Collections framework to merge two Static method for a sorted collection. It merges two sorted sets into a new sorted set, maintaining the original sort order.
Syntax
<code class="java">public static <T> List<T> merge(SortedMap<T, Double> a, SortedMap<T, Double> b)</code>
Parameters
Return value
A new sorted collection, Contains all elements in a and b, in sorted order.
Usage method
The merge() method can be used as follows:
<code class="java">import java.util.*; public class MergeExample { public static void main(String[] args) { // 创建两个已排序的集合 SortedMap<Integer, Double> map1 = new TreeMap<>(); map1.put(1, 0.5); map1.put(3, 0.7); map1.put(5, 0.9); SortedMap<Integer, Double> map2 = new TreeMap<>(); map2.put(2, 0.6); map2.put(4, 0.8); // 合并两个集合 SortedMap<Integer, Double> mergedMap = Collections.merge(map1, map2, (a, b) -> a + b); // 打印合并后的集合 System.out.println(mergedMap); } }</code>
Output
<code>{1=0.5, 2=0.6, 3=0.7, 4=0.8, 5=0.9}</code>
In In this example, two sorted collections are merged into a new sorted collection that contains all elements and preserves the sorted order.
Notes
The above is the detailed content of How to use merge in java. For more information, please follow other related articles on the PHP Chinese website!