wok*_*kow 6 java collections java-8 java-stream
我想将列表转换为映射,使用键值只有两个字符串值.然后作为值只列出包含来自输入列表的奇数或偶数索引位置的元素的字符串.这是旧时尚代码:
Map<String, List<String>> map = new HashMap<>();
List<String> list = Arrays.asList("one", "two", "three", "four");
map.put("evenIndex", new ArrayList<>());
map.put("oddIndex", new ArrayList<>());
for (int i = 0; i < list.size(); i++) {
if(i % 2 == 0)
map.get("evenIndex").add(list.get(i));
else
map.get("oddIndex").add(list.get(i));
}
Run Code Online (Sandbox Code Playgroud)
如何使用流将此代码转换为Java 8以获得此结果?
{evenIndex=[one, three], oddIndex=[two, four]}
Run Code Online (Sandbox Code Playgroud)
我当前的混乱尝试需要修改列表元素,但绝对必须是更好的选择.
List<String> listModified = Arrays.asList("++one", "two", "++three", "four");
map = listModified.stream()
.collect(Collectors.groupingBy(
str -> str.startsWith("++") ? "evenIndex" : "oddIndex"));
Run Code Online (Sandbox Code Playgroud)
或者有人帮我解决这个错误的解决方案?
IntStream.range(0, list.size())
.boxed()
.collect(Collectors.groupingBy( i -> i % 2 == 0 ? "even" : "odd",
Collectors.toMap( (i -> i ) , i -> list.get(i) ) )));
Run Code Online (Sandbox Code Playgroud)
返回此:
{even={0=one, 2=three}, odd={1=two, 3=four}}
Run Code Online (Sandbox Code Playgroud)
您在对索引进行流式传输时走在正确的轨道上:
import static java.util.stream.Collectors.groupingBy;
import static java.util.stream.Collectors.mapping;
import static java.util.stream.Collectors.toList;
IntStream.range(0,list.size())
.boxed()
.collect(groupingBy(
i -> i % 2 == 0 ? "even" : "odd",
mapping(list::get, toList())
));
Run Code Online (Sandbox Code Playgroud)
如果您同意将地图编入索引,则boolean可以使用partitioningBy:
IntStream.range(0, list.size())
.boxed()
.collect(partitioningBy(
i -> i % 2 == 0,
mapping(list::get, toList())
));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
240 次 |
| 最近记录: |