[英]add elements to map if Map<String , Stack<Integer>> map… in java
I have a Map
collection which maps String
to Stack<Integer
how can I put my stacks to this map?我有一个
Map
集合,它将String
映射到Stack<Integer
我怎样才能将我的堆栈放到这个 map? I've tried this so far but couldn't succeed.到目前为止,我已经尝试过了,但无法成功。
Map<String,Stack<Integer>> map=new HashMap<>();
map.put("abc",new Stack<Integer>().push(123));
You can use computeIfAbsent() method which was added in Java 8:您可以使用 Java 8 中添加的computeIfAbsent()方法:
Map<String, Stack<Integer>> map=new HashMap<>();
map.computeIfAbsent("abc", k -> new Stack<>()).push(123);
Since Stack#push method returns an Integer
here.由于Stack#push方法在此处返回
Integer
。 You can modify your code this way to achieve it:您可以通过这种方式修改代码来实现它:
Map<String, Stack<Integer>> map=new HashMap<>();
Stack<Integer> stack = new Stack<>();
stack.push(123);
map.put("abc", stack);
Update:更新:
After looking at your comment on my answer.看了你对我的回答的评论。 I think you want to accomplish something like this:
我想你想完成这样的事情:
Map<String, Deque<Integer>> map = new HashMap<>();
Deque<Integer> deque = new ArrayDeque<>(); // use Deque instead of Stack
map.put("abc", deque); // putting the Deque in Map
map.get("abc").add(12);
map.get("abc").add(34);
map.get("abc").add(56);
map.get("abc").add(78);
System.out.println("Before removing: " + map);
map.get("abc").remove(); // removing first element
System.out.println("After removing: " + map);
Output: Output:
Before removing: {abc=[12, 34, 56, 78]}
After removing: {abc=[34, 56, 78]}
Your implementation is wrong here.您的实现在这里是错误的。 You have to create object first of type
Stack<Integer>
.您必须首先创建类型为
Stack<Integer>
的 object 。 As you have specified Stack<Integer>
as values
you should have to create Object
of that type.由于您已将
Stack<Integer>
指定为values
,因此您应该必须创建该类型的Object
。 Return type of push
is of type
itself so it cause error in your case. push
的返回type
本身就是类型,因此在您的情况下会导致错误。
Map<String,Stack<Integer>> map=new HashMap<>();
Stack<Integer> stack = new Stack<Integer>();
stack.push(123);
map.put("abc",stack);
First you need to fetch the stack, that you want to update, then you need to update the stack with the new element, and finally use the property of map, that replaces the elements, of the map already exists.首先,您需要获取要更新的堆栈,然后需要使用新元素更新堆栈,最后使用 map 的替换元素的 map 的属性。
Stack<Integer> st = map.getOrDefault("abc",new Stack<Integer>());
st.push(123);
map.put("abc",st);
use this:用这个:
BiFunction<Stack<Integer>, Integer, Stack<Integer>> bi = (s, i) -> {
s.push(i);
return s;
};
map.put("abc", bi.apply(map.get("abc"), 134));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.