使用Stream流获取treeMap

    TreeMap<Long, String> treeMap = new TreeMap<>();
     TreeMap<Long, String> map = treeMap.entrySet().stream()   		
     									.collect(Collectors.toMap(entry -> entry.getKey(), entry -> entry.getValue(), (oldValue, newValue) -> newValue, TreeMap::new));

分别设置map的k,v,key冲突后的取值策略,生成的map类型

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
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.

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值