英文:
Place condition on keySet() based on value - HashMap --> stream to ArrayList
问题
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static java.util.stream.Collectors.toList;
public class Test {
public static void main(String[] args) {
Map<String, List<Double>> grandMap = new HashMap<>();
grandMap.put("ME", Arrays.asList(3.6, 6584.60));
grandMap.put("ERIC", Arrays.asList(5.6, 6.5));
grandMap.put("MARIA", Arrays.asList(6.97, 6.5));
grandMap.put("GITA", Arrays.asList(5.5, 652.1));
List<String> select_values = grandMap
.entrySet()
.stream()
.filter(map -> map.getValue().get(1).equals(6.5))
.map(x -> x.getKey())
.distinct()
.collect(toList());
}
}
英文:
little help please for newbie to streams. I am trying to get the arraylist select_values from the grandMap whose value at index 1 equals the double 6.5. A little lost with the script specifically attempting to save the key to a list. Basically select_values should be an arraylist of Strings of size 2 containing they key themselves "ERIC" and "MARIA". Thank you
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static java.util.stream.Collectors.toList;
public class Test {
public static void main(String[] args) {
Map<String, List<Double>> grandMap = new HashMap<>();
grandMap.put("ME", Arrays.asList(3.6, 6584.60));
grandMap.put("ERIC", Arrays.asList(5.6, 6.5));
grandMap.put("MARIA", Arrays.asList(6.97, 6.5));
grandMap.put("GITA", Arrays.asList(5.5, 652.1));
List<String> select_values = grandMap
.entrySet()
.stream()
.filter(map -> map.getValue().get(1).equals(6.5))
.map(x -> x.getKey())
.distinct()
.collect(toList::new);
}
}
答案1
得分: 1
替代 toList::new
,你应该使用 Collectors.toList()
:
List<String> select_values = grandMap
.entrySet()
.stream()
.filter(entry -> entry.getValue().get(1) == 6.5)
.map(Map.Entry::getKey)
.distinct()
.collect(Collectors.toList());
附注 1:由于你在比较 double
类型,我建议使用 ==
而不是 equals
。
附注 2:你可以使用操作符 Map.Entry::getKey
替代 entry -> entry.getKey()
进行映射。
英文:
Instead of toList::new
, you should collect using Collectors.toList()
:
List<String> select_values = grandMap
.entrySet()
.stream()
.filter(entry -> entry.getValue().get(1) == 6.5)
.map(Map.Entry::getKey)
.distinct()
.collect(Collectors.toList());
Sidenote 1: Since you are comparing doubles
, I would use ==
instead of equals
.
Sidenote 2: You can use operator Map.Entry::getKey
instead of entry -> entry.getKey()
for mapping.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论