java list stream treemap
时间: 2023-10-31 15:49:14 浏览: 132
Java List: A List is an interface in Java that extends the Collection interface. It is an ordered collection of elements that can have duplicates.
Java Stream: A Java Stream is a sequence of elements that can be processed in parallel or sequentially. Streams are used to manipulate collections of objects and can be used to perform operations on collections such as filtering, sorting, mapping, and more.
Java TreeMap: A TreeMap is a class in Java that implements the Map interface. It is a sorted map that stores key-value pairs in a tree structure. The keys are sorted in a natural order or by a specified Comparator. TreeMap is useful when you need to maintain a sorted order of keys.
Using Streams with List and TreeMap:
Java Stream can be used with List and TreeMap to perform various operations on the elements of these collections. Here are some examples:
1. Filtering elements from a List using Stream:
List<String> names = Arrays.asList("John", "Jane", "Mary", "Susan");
List<String> filteredNames = names.stream()
.filter(name -> name.startsWith("J"))
.collect(Collectors.toList());
In this example, we have a List of names and we are using a Stream to filter out the names that start with the letter "J".
2. Sorting elements in a TreeMap using Stream:
TreeMap<Integer, String> map = new TreeMap<>();
map.put(1, "John");
map.put(2, "Jane");
map.put(3, "Mary");
map.put(4, "Susan");
Map<Integer, String> sortedMap = map.entrySet().stream()
.sorted(Map.Entry.comparingByKey())
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
(oldValue, newValue) -> oldValue, LinkedHashMap::new));
In this example, we have a TreeMap with integer keys and string values. We are using a Stream to sort the key-value pairs by the key in ascending order and then store them in a new LinkedHashMap.
阅读全文