基本上我在寻找一种避免与
一起工作的方法entry -> entry.getValue
和
entry -> entry.getKey
类似于 Map.forEach() 的作用。
要是我能找到一种方法像 map.stream().filter((k,v) -> )... 那样工作就好了
这个接口(interface)好像叫BiConsumer。 也许有一个转换器到 BiConsumer 或一个 Stream.generate() 某种方式
最佳答案
因为这是一个重复的问题,我会把一个完整的解决方案扔进戒指。它是一种 PairStream 类型,默认情况下是普通 Stream 的简单包装器(不过,作为一个 interface,替代方案是可能的)。
它着重于提供方便的中间操作和那些不能通过调用方法keys()、values()或entries() 返回一个传统的单元素 Stream 并链接一个终端操作。因此,例如,PairStream.from(map).filterValue(predicate).keys().findAny() 是获取映射值与谓词匹配的键的直接方法。 filterValue 是一个方便的中间操作,keys 返回普通的 Stream 允许对键进行任意终端操作。
一些例子
Map<String,Integer> m=new HashMap<>();
m.put("foo", 5);
m.put("bar", 7);
m.put("baz", 42);
// {b=49, f=5}
Map<Character,Integer> m2=PairStream.from(m)
.mapKey(s->s.charAt(0))
.toMap(Integer::sum);
// foo bar
String str=PairStream.from(m)
.filterValue(i->i<30)
.keys().sorted(Comparator.reverseOrder())
.collect(Collectors.joining(" "));
Map<String,Integer> map=new HashMap<>();
map.put("muhv~", 26);
map.put("kfool", 3);
String str = PairStream.from(map)
.sortedByValue(Comparator.naturalOrder())
.flatMapToInt((s,i)->s.codePoints().map(c->c^i))
.collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append)
.toString();
这是完整的类(我还没有测试所有操作,但大部分都是直截了当的):
import java.util.*;
import java.util.function.*;
import java.util.stream.*;
public interface PairStream<K,V> {
static <K,V> PairStream<K,V> from(Map<K,V> map) {
return from(map.entrySet().stream());
}
static <K,V> PairStream<K,V> from(Stream<Map.Entry<K,V>> s) {
return ()->s;
}
static <K,V> PairStream<K,V> from(Stream<K> s, Function<? super K, ? extends V> f) {
return ()->s.map(k->new AbstractMap.SimpleImmutableEntry<>(k, f.apply(k)));
}
default PairStream<K,V> distinct() {
return from(entries().distinct());
}
default PairStream<K,V> peek(BiConsumer<? super K, ? super V> action) {
return from(entries().peek(e->action.accept(e.getKey(), e.getValue())));
}
default PairStream<K,V> skip(long n) {
return from(entries().skip(n));
}
default PairStream<K,V> limit(long maxSize) {
return from(entries().limit(maxSize));
}
default PairStream<K,V> filterKey(Predicate<? super K> mapper) {
return from(entries().filter(e->mapper.test(e.getKey())));
}
default PairStream<K,V> filterValue(Predicate<? super V> mapper) {
return from(entries().filter(e->mapper.test(e.getValue())));
}
default PairStream<K,V> filter(BiPredicate<? super K, ? super V> mapper) {
return from(entries().filter(e->mapper.test(e.getKey(), e.getValue())));
}
default <R> PairStream<R,V> mapKey(Function<? super K,? extends R> mapper) {
return from(entries().map(e->new AbstractMap.SimpleImmutableEntry<>(
mapper.apply(e.getKey()), e.getValue()
)));
}
default <R> PairStream<K,R> mapValue(Function<? super V,? extends R> mapper) {
return from(entries().map(e->new AbstractMap.SimpleImmutableEntry<>(
e.getKey(), mapper.apply(e.getValue())
)));
}
default <R> Stream<R> map(BiFunction<? super K, ? super V,? extends R> mapper) {
return entries().map(e->mapper.apply(e.getKey(), e.getValue()));
}
default DoubleStream mapToDouble(ToDoubleBiFunction<? super K, ? super V> mapper) {
return entries().mapToDouble(e->mapper.applyAsDouble(e.getKey(), e.getValue()));
}
default IntStream mapToInt(ToIntBiFunction<? super K, ? super V> mapper) {
return entries().mapToInt(e->mapper.applyAsInt(e.getKey(), e.getValue()));
}
default LongStream mapToLong(ToLongBiFunction<? super K, ? super V> mapper) {
return entries().mapToLong(e->mapper.applyAsLong(e.getKey(), e.getValue()));
}
default <RK,RV> PairStream<RK,RV> flatMap(
BiFunction<? super K, ? super V,? extends PairStream<RK,RV>> mapper) {
return from(entries().flatMap(
e->mapper.apply(e.getKey(), e.getValue()).entries()));
}
default <R> Stream<R> flatMapToObj(
BiFunction<? super K, ? super V,? extends Stream<R>> mapper) {
return entries().flatMap(e->mapper.apply(e.getKey(), e.getValue()));
}
default DoubleStream flatMapToDouble(
BiFunction<? super K, ? super V,? extends DoubleStream> mapper) {
return entries().flatMapToDouble(e->mapper.apply(e.getKey(), e.getValue()));
}
default IntStream flatMapToInt(
BiFunction<? super K, ? super V,? extends IntStream> mapper) {
return entries().flatMapToInt(e->mapper.apply(e.getKey(), e.getValue()));
}
default LongStream flatMapToLong(
BiFunction<? super K, ? super V,? extends LongStream> mapper) {
return entries().flatMapToLong(e->mapper.apply(e.getKey(), e.getValue()));
}
default PairStream<K,V> sortedByKey(Comparator<? super K> comparator) {
return from(entries().sorted(Map.Entry.comparingByKey(comparator)));
}
default PairStream<K,V> sortedByValue(Comparator<? super V> comparator) {
return from(entries().sorted(Map.Entry.comparingByValue(comparator)));
}
default boolean allMatch(BiPredicate<? super K,? super V> predicate) {
return entries().allMatch(e->predicate.test(e.getKey(), e.getValue()));
}
default boolean anyMatch(BiPredicate<? super K,? super V> predicate) {
return entries().anyMatch(e->predicate.test(e.getKey(), e.getValue()));
}
default boolean noneMatch(BiPredicate<? super K,? super V> predicate) {
return entries().noneMatch(e->predicate.test(e.getKey(), e.getValue()));
}
default long count() {
return entries().count();
}
Stream<Map.Entry<K,V>> entries();
default Stream<K> keys() {
return entries().map(Map.Entry::getKey);
}
default Stream<V> values() {
return entries().map(Map.Entry::getValue);
}
default Optional<Map.Entry<K,V>> maxByKey(Comparator<? super K> comparator) {
return entries().max(Map.Entry.comparingByKey(comparator));
}
default Optional<Map.Entry<K,V>> maxByValue(Comparator<? super V> comparator) {
return entries().max(Map.Entry.comparingByValue(comparator));
}
default Optional<Map.Entry<K,V>> minByKey(Comparator<? super K> comparator) {
return entries().min(Map.Entry.comparingByKey(comparator));
}
default Optional<Map.Entry<K,V>> minByValue(Comparator<? super V> comparator) {
return entries().min(Map.Entry.comparingByValue(comparator));
}
default void forEach(BiConsumer<? super K, ? super V> action) {
entries().forEach(e->action.accept(e.getKey(), e.getValue()));
}
default void forEachOrdered(BiConsumer<? super K, ? super V> action) {
entries().forEachOrdered(e->action.accept(e.getKey(), e.getValue()));
}
default Map<K,V> toMap() {
return entries().collect(
Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
}
default Map<K,V> toMap(BinaryOperator<V> valAccum) {
return entries().collect(
Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, valAccum));
}
}
关于java - 有什么方法可以流式传输像 "(k,v)"这样的 map 而不是使用(条目)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29239377/
我正在学习如何使用Nokogiri,根据这段代码我遇到了一些问题:require'rubygems'require'mechanize'post_agent=WWW::Mechanize.newpost_page=post_agent.get('http://www.vbulletin.org/forum/showthread.php?t=230708')puts"\nabsolutepathwithtbodygivesnil"putspost_page.parser.xpath('/html/body/div/div/div/div/div/table/tbody/tr/td/div
总的来说,我对ruby还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用
类classAprivatedeffooputs:fooendpublicdefbarputs:barendprivatedefzimputs:zimendprotecteddefdibputs:dibendendA的实例a=A.new测试a.foorescueputs:faila.barrescueputs:faila.zimrescueputs:faila.dibrescueputs:faila.gazrescueputs:fail测试输出failbarfailfailfail.发送测试[:foo,:bar,:zim,:dib,:gaz].each{|m|a.send(m)resc
我正在尝试设置一个puppet节点,但rubygems似乎不正常。如果我通过它自己的二进制文件(/usr/lib/ruby/gems/1.8/gems/facter-1.5.8/bin/facter)在cli上运行facter,它工作正常,但如果我通过由rubygems(/usr/bin/facter)安装的二进制文件,它抛出:/usr/lib/ruby/1.8/facter/uptime.rb:11:undefinedmethod`get_uptime'forFacter::Util::Uptime:Module(NoMethodError)from/usr/lib/ruby
我正在尝试测试是否存在表单。我是Rails新手。我的new.html.erb_spec.rb文件的内容是:require'spec_helper'describe"messages/new.html.erb"doit"shouldrendertheform"dorender'/messages/new.html.erb'reponse.shouldhave_form_putting_to(@message)with_submit_buttonendendView本身,new.html.erb,有代码:当我运行rspec时,它失败了:1)messages/new.html.erbshou
我在从html页面生成PDF时遇到问题。我正在使用PDFkit。在安装它的过程中,我注意到我需要wkhtmltopdf。所以我也安装了它。我做了PDFkit的文档所说的一切......现在我在尝试加载PDF时遇到了这个错误。这里是错误:commandfailed:"/usr/local/bin/wkhtmltopdf""--margin-right""0.75in""--page-size""Letter""--margin-top""0.75in""--margin-bottom""0.75in""--encoding""UTF-8""--margin-left""0.75in""-
我有一个模型:classItem项目有一个属性“商店”基于存储的值,我希望Item对象对特定方法具有不同的行为。Rails中是否有针对此的通用设计模式?如果方法中没有大的if-else语句,这是如何干净利落地完成的? 最佳答案 通常通过Single-TableInheritance. 关于ruby-on-rails-Rails-子类化模型的设计模式是什么?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.co
我想了解Ruby方法methods()是如何工作的。我尝试使用“ruby方法”在Google上搜索,但这不是我需要的。我也看过ruby-doc.org,但我没有找到这种方法。你能详细解释一下它是如何工作的或者给我一个链接吗?更新我用methods()方法做了实验,得到了这样的结果:'labrat'代码classFirstdeffirst_instance_mymethodenddefself.first_class_mymethodendendclassSecond使用类#returnsavailablemethodslistforclassandancestorsputsSeco
我正在使用的第三方API的文档状态:"[O]urAPIonlyacceptspaddedBase64encodedstrings."什么是“填充的Base64编码字符串”以及如何在Ruby中生成它们。下面的代码是我第一次尝试创建转换为Base64的JSON格式数据。xa=Base64.encode64(a.to_json) 最佳答案 他们说的padding其实就是Base64本身的一部分。它是末尾的“=”和“==”。Base64将3个字节的数据包编码为4个编码字符。所以如果你的输入数据有长度n和n%3=1=>"=="末尾用于填充n%
我主要使用Ruby来执行此操作,但到目前为止我的攻击计划如下:使用gemsrdf、rdf-rdfa和rdf-microdata或mida来解析给定任何URI的数据。我认为最好映射到像schema.org这样的统一模式,例如使用这个yaml文件,它试图描述数据词汇表和opengraph到schema.org之间的转换:#SchemaXtoschema.orgconversion#data-vocabularyDV:name:namestreet-address:streetAddressregion:addressRegionlocality:addressLocalityphoto:i