考虑Person类有三个字段名称(String),age(int),salary(double).
我想创建一个名称为键和值为pay(而不是Person对象本身)的映射,如果key不唯一,则使用linkedList保存所有重复键的值.
我指的是下面给出的链接中给出的解决方案: 在Java 8中从流中以惯用方式创建多值Map 但仍不清楚如何使用Salary作为值创建hashmap.
我可以map<String, List<Double>>用forEach()创建.代码如下:
List<Person> persons= new ArrayList<>();
persons.add(p1);
persons.add(p2);
persons.add(p3);
persons.add(p4);
Map<String, List<Double>> personsByName = new HashMap<>();
persons.forEach(person ->
personsByName.computeIfAbsent(person.getName(), key -> new LinkedList<>())
.add(person.getSalary())
);
Run Code Online (Sandbox Code Playgroud)
但我正在尝试使用"groupingBy&collect"来创建地图.如果我们想将Person对象本身作为值,则代码如下:
Map<String, List<Person>> personsByNameGroupingBy = persons.stream()
.collect(Collectors.groupingBy(Person::getName, Collectors.toList()));
Run Code Online (Sandbox Code Playgroud)
但是我想创建一个薪水作为价值的地图,如下所示:
Map<String, List<Double>>
Run Code Online (Sandbox Code Playgroud)
如何实现这种情况?
我想通过对Map的键应用一些操作来创建一个HashMap<String,Integer>现有HashMap<String,Integer>的.假设我有一个String->
String sampleString= "SOSSQRSOP";`
Run Code Online (Sandbox Code Playgroud)
然后通过从下面的字符串中只取3个字符(将0作为值)创建一个hashmap:
Map<String, Integer> messages= new HashMap<>();
messages.put("SOS",0);
messages.put("SQR",0);
messages.put("SOP",0);
Run Code Online (Sandbox Code Playgroud)
实际任务是使用映射中的每个键从给定字符串"SOS"中查找不同字符的总数,并将no指定给每个键的值.如下(最终结果):
Map<String, Integer> messages= new HashMap<>();
messages.put("SOS",0);
messages.put("SQR",2);
messages.put("SOP",1);
Run Code Online (Sandbox Code Playgroud)
所以我使用下面给出的流在java8中编写代码:
Map<String,Integer> result= messages
.entrySet().stream()
.collect(Collectors.toMap(e-> e.getKey(),
e-> e.getKey().stream()
.forEach(x-> {
if(!"SOS".equals(x)){
char[] characters= {'S','O','S'};
char[] message= x.toCharArray();
for(int i=0; i< characters.length;i++){
int index=0;
if(characters[i] != message[i]){
messages.put(e.getKey(),++index);
}
}
}
});
));
Run Code Online (Sandbox Code Playgroud)
我收到编译错误.任何人都可以帮助我使用流编写代码.
编辑:还请描述其他方法来做到这一点.在我的例子中,BTW需要从给定的字符串创建第一个hashmap.