您好我是java函数式编程的新手。我试图过滤一个地图,如果元素在集合中,跳过它;否则处理它并将其放入集合中。 但我发现它看起来像保持静态(不是由终端操作更新)
public class StreamMap {
public static void main(String[] args) {
Map<Integer, String> HOSTING = new HashMap<>();
HOSTING.put(1, "linode.com");
HOSTING.put(2, "heroku.com");
HOSTING.put(3, "digitalocean.com");
HOSTING.put(4, "aws.amazon.com");
HOSTING.put(5, "aws.amazon.com");
Set<String> s = new HashSet();
//Map -> Stream -> Filter -> Map
HOSTING.entrySet().stream()
.filter(map -> !s.contains(map.getValue()))
.collect(Collectors.toMap(p -> p.getKey(), p -> p.getValue())).forEach((k, v) -> {System.out.println("show:" + String.valueOf(k) + v);s.add(v);});
}
}
返回
show:linode.com
show:heroku.com
show:digitalocean.com
show:aws.amazon.com
show:aws.amazon.com //I don't want this to be returns because it's already done before
答案 0 :(得分:1)
尝试一下谎言:
HOSTING.entrySet()
.stream()
.filter(map -> s.add(map.getValue()))
.collect(Collectors.toMap(p -> p.getKey(), p -> p.getValue())).forEach((k, v) -> {
System.out.println("show:" + v);
});
答案 1 :(得分:0)
另一种方法是您可以将地图值转换为列表,然后您可以轻松地在列表中使用 Distinct()
List<String> result = HOSTING.values().stream().collect(Collectors.toList()); //convert map to list
result.stream().distinct().collect(Collectors.toList()); // filtering the list
System.out.println(result);