stream能够更加优雅的处理集合、数组等数据,让我们写出更加直观、可读性更高的数据处理代码
set、list能够直接通过.stream()的形式创建steam流
而数组需要通过 Arrays.stream(arr); Stream.of(arr);
map需要通过entrySet()方法,先将map转换成Set<Map.Entry<String, Integer>> set对象,再通过set.stream()的方式转换
stream中的api比较多
/**
* @author Pzi
* @create 2022-12-30 13:22
*/
@SpringBootTest
@RunWith(SpringRunner.class)
public class Test2 {
@Test
public void test1() {
List<Author> authors = S.getAuthors();
authors
.stream()
.distinct()
.filter(author -> {
// 满足这个条件,那么才会被筛选到继续留在stream中
return author.getAge() < 18;
})
.forEach(author -> System.out.println(author.getAge()));
}
// 对双列集合map的stream操作
@Test
public void test2() {
Map<String, Integer> map = new HashMap<>();
map.put("蜡笔小新", 19);
map.put("黑子", 17);
map.put("日向翔阳", 16);
//entrySet是一个包含多个Entry的Set数据结构,Entry是key-val型的数据结构
Set<Map.Entry<String, Integer>> entries = map.entrySet();
entries.stream()
.filter(entry -> {
return entry.getValue() > 17;
})
.forEach(entry -> {
System.out.println(entry);
});
}
// stream的map操作,提取stream中对象的属性,或者计算
@Test
public void test3() {
List<Author> authors = S.getAuthors();
authors
.stream()
.map(author -> author.getName())
.forEach(name -> System.out.println(name));
System.out.println(1);
authors
.stream()
.map(author -> author.getAge())
.map(age -> age + 10)
.forEach(age -> System.out.println(age));
}
// steam的sorted操作
@Test
public void test4() {
List<Author> authors = S.getAuthors();
authors
.stream()
.distinct()
.sorted(((o1, o2) -> o2.getAge() - o1.getAge()))
.skip(1)
.forEach(author -> System.out.println(author.getName() + " " + author.getAge()));
}
// flapMap的使用,重新组装,改变stream流中存放的对象
@Test
public void test5() {
// 打印所有书籍的名字。要求对重复的元素进行去重。
List<Author> authors = S.getAuthors();
authors.stream()
.flatMap(author -> author.getBooks().stream())
.distinct()
.forEach(book -> System.out.println(book.getName()));
authors.stream()
// 将以authors为对象的stream流 组装成 以book为对象的strem流
.flatMap(author -> author.getBooks().stream())
.distinct()
// 将每个book中的category转换成数组,然后将[x1,x2]代表分类的数组转换成stream流,然后使用flapMap将该数组stream流组装成以x1,x2...为对象的stream流
// 将以book为对象的strem流 组装成 以category为对象的stream流
.flatMap(book -> Arrays.stream(book.getCategory().split(",")))
.distinct()
.forEach(category -> System.out.println(category));
}
// 数组转换成stream流
@Test
public void test6() {
Integer[] arr = {1, 2, 3, 4, 5};
Stream<Integer> stream = Arrays.stream(arr);
stream
.filter(integer -> integer > 3)
.forEach(integer -> System.out.println(integer));
}
@Test
public void test7() {
// 打印这些作家的所出书籍的数目,注意删除重复元素。
List<Author> authors = S.getAuthors();
long count = authors
.stream()
.flatMap(author -> author.getBooks().stream())
.distinct()
.count();
System.out.println(count);
}
// max() min()
@Test
public void test8() {
// 分别获取这些作家的所出书籍的最高分和最低分并打印。
List<Author> authors = S.getAuthors();
Optional<Integer> max = authors.stream()
.flatMap(author -> author.getBooks().stream())
.map(book -> book.getScore())
.max((score1, score2) -> score1 - score2);
Optional<Integer> min = authors.stream()
.flatMap(author -> author.getBooks().stream())
.map(book -> book.getScore())
.min((score1, score2) -> score1 - score2);
System.out.println(max.get());
System.out.println(min.get());
}
// stream 的 collect()
@Test
public void test9() {
// 获取所有作者名字
List<Author> authors = S.getAuthors();
Set<String> collect = authors.stream()
.map(author -> author.getName())
.collect(Collectors.toSet());
System.out.println(collect);
//获取一个所有书名的Set集合。
Set<String> collect1 = authors.stream()
.flatMap(author -> author.getBooks().stream())
.map(book -> book.getName())
.collect(Collectors.toSet());
System.out.println(collect1);
// 获取一个Map集合,map的key为作者名,value为List<Book>
Map<String, List<Book>> collect2 = authors.stream()
.distinct()
.collect(Collectors.toMap(author -> author.getName(), author -> author.getBooks()));
System.out.println(collect2);
}
// anyMatch
@Test
public void test10() {
List<Author> authors = S.getAuthors();
boolean b = authors.stream()
.anyMatch(author -> author.getAge() > 29);
System.out.println(b);
}
// allMatch
@Test
public void test11() {
List<Author> authors = S.getAuthors();
boolean b = authors.stream()
.allMatch(author -> author.getAge() > 18);
System.out.println(b);
}
// findFirst
@Test
public void test12() {
List<Author> authors = S.getAuthors();
Optional<Author> first = authors.stream()
.sorted(((o1, o2) -> o1.getAge() - o2.getAge()))
.findFirst();
first.ifPresent(author -> System.out.println(author));
}
// reduce() 的使用
@Test
public void test13() {
// 使用reduce求所有作者年龄的和
List<Author> authors = S.getAuthors();
Integer sum = authors.stream()
.distinct()
.map(author -> author.getAge())
.reduce(0, (result, element) -> result + element);
// .reduce(0, (result, element) -> result + element);
System.out.println(sum);
}
@Test
public void test14() {
// 使用reduce求所有作者中年龄的最小值
List<Author> authors = S.getAuthors();
Integer minAge = authors.stream()
.map(author -> author.getAge())
.reduce(Integer.MAX_VALUE, (res, ele) -> res > ele ? ele : res);
System.out.println(minAge);
}
// 没有初始值的reduce()使用
@Test
public void test15() {
List<Author> authors = S.getAuthors();
Optional<Integer> age = authors.stream()
.map(author -> author.getAge())
.reduce((res, ele) -> res > ele ? ele : res);
System.out.println(age.get());
}
// Optional对象的封装,orElseGet的使用
@Test
public void test16() {
Optional<Author> authorOptional = Optional.ofNullable(null);
Author author1 = authorOptional.orElseGet(() -> new Author(1l, "1", 1, "1", null));
System.out.println(author1);
// authorOptional.ifPresent(author -> System.out.println(author.getName()));
}
@Test
public void test17() {
Optional<Author> authorOptional = Optional.ofNullable(null);
try {
Author author = authorOptional.orElseThrow((Supplier<Throwable>) () -> new RuntimeException("exception"));
System.out.println(author.getName());
} catch (Throwable throwable) {
throwable.printStackTrace();
}
}
// Optional的filter()方法
// ifPresent()可以安全消费Optional中包装的对象
@Test
public void test18() {
Optional<Author> optionalAuthor = Optional.ofNullable(S.getAuthors().get(0));
optionalAuthor
.filter(author -> author.getAge() > 14)
.ifPresent(author -> System.out.println(author));
}
// Optional的isPresent()方法,用来判断该Optional是否包装了对象
@Test
public void test19() {
Optional<Author> optionalAuthor = Optional.ofNullable(S.getAuthors().get(0));
boolean present = optionalAuthor.isPresent();
if (present) {
System.out.println(optionalAuthor.get().getName());
}
}
// Optional的map(),将一个 Optional 转换成另一个 Optional
@Test
public void test20() {
Optional<Author> optionalAuthor = Optional.ofNullable(S.getAuthors().get(0));
optionalAuthor.ifPresent(author -> System.out.println(author.getBooks()));
Optional<List<Book>> books = optionalAuthor.map(author -> author.getBooks());
books.ifPresent(books1 -> System.out.println(books.get()));
}
// 类的静态方法
@Test
public void test21() {
List<Author> authors = S.getAuthors();
authors.stream()
.map(author -> author.getAge())
.map(integer -> String.valueOf(integer));
// lambda方法体中只有一行代码
// .map(String::valueOf);
}
// 对象的实例方法
@Test
public void test22() {
List<Author> authors = S.getAuthors();
Stream<Author> authorStream = authors.stream();
StringBuilder sb = new StringBuilder();
authorStream.map(author -> author.getName())
// lambda方法体中只有一行代码,且将参数全部按照顺序传入这个重写方法中
.forEach(str -> sb.append(str));
}
// 接口中只有一个抽象方法称为函数式接口
// 方法引用的条件是:lambda方法体中只有一行方法
// 构造器的方法引用
@Test
public void test23() {
List<Author> authors = S.getAuthors();
authors.stream()
.map(Author::getName)
.map(StringBuilder::new)
.map(stringBuilder -> stringBuilder.append("abc"))
.forEach(System.out::println);
}
// steam提供的处理基本数据类型,避免频繁的自动拆/装箱,从而达到省时,提高性能
@Test
public void test24() {
List<Author> authors = S.getAuthors();
authors.stream()
.map(author -> author.getAge())
.map(age -> age + 10)
.filter(age -> age > 18)
.map(age -> age + 2)
.forEach(System.out::println);
authors.stream()
.mapToInt(author -> author.getAge())
.map(age -> age + 10)
.filter(age -> age > 18)
.map(age -> age + 2)
.forEach(System.out::println);
}
@Test
public void test25() {
List<Author> authors = S.getAuthors();
authors.stream()
.parallel()
.map(author -> author.getAge())
.peek(integer -> System.out.println(integer+" "+Thread.currentThread().getName()))
.reduce(new BinaryOperator<Integer>() {
@Override
public Integer apply(Integer result, Integer ele) {
return result + ele;
}
}).ifPresent(sum -> System.out.println(sum));
}
}
lambda表达式只关心 形参列表 和 方法体
用在重写抽象方法的时候,一般都是采用lambda表达式的方式来重写
函数式接口:接口中只有一个抽象方法,就称之为函数式接口。在Java中Consumer,Funciton,Supplier
方法引用:当lambda表达式的方法体中只有一行代码,并且符合一些规则,就可以将该行代码转换成方法引用的形式
可以直接使用idea的提示自动转换
这只是一个语法糖,能看懂代码就行,不要过于纠结
我正在学习如何使用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
我想了解Ruby方法methods()是如何工作的。我尝试使用“ruby方法”在Google上搜索,但这不是我需要的。我也看过ruby-doc.org,但我没有找到这种方法。你能详细解释一下它是如何工作的或者给我一个链接吗?更新我用methods()方法做了实验,得到了这样的结果:'labrat'代码classFirstdeffirst_instance_mymethodenddefself.first_class_mymethodendendclassSecond使用类#returnsavailablemethodslistforclassandancestorsputsSeco
我在我的项目中添加了一个系统来重置用户密码并通过电子邮件将密码发送给他,以防他忘记密码。昨天它运行良好(当我实现它时)。当我今天尝试启动服务器时,出现以下错误。=>BootingWEBrick=>Rails3.2.1applicationstartingindevelopmentonhttp://0.0.0.0:3000=>Callwith-dtodetach=>Ctrl-CtoshutdownserverExiting/Users/vinayshenoy/.rvm/gems/ruby-1.9.3-p0/gems/actionmailer-3.2.1/lib/action_mailer
设置:狂欢ruby1.9.2高线(1.6.13)描述:我已经相当习惯在其他一些项目中使用highline,但已经有几个月没有使用它了。现在,在Ruby1.9.2上全新安装时,它似乎不允许在同一行回答提示。所以以前我会看到类似的东西:require"highline/import"ask"Whatisyourfavoritecolor?"并得到:Whatisyourfavoritecolor?|现在我看到类似的东西:Whatisyourfavoritecolor?|竖线(|)符号是我的终端光标。知道为什么会发生这种变化吗? 最佳答案
我已经从我的命令行中获得了一切,所以我可以运行rubymyfile并且它可以正常工作。但是当我尝试从sublime中运行它时,我得到了undefinedmethod`require_relative'formain:Object有人知道我的sublime设置中缺少什么吗?我正在使用OSX并安装了rvm。 最佳答案 或者,您可以只使用“require”,它应该可以正常工作。我认为“require_relative”仅适用于ruby1.9+ 关于ruby-主要:Objectwhenrun
我想在一个没有Sass引擎的类中使用Sass颜色函数。我已经在项目中使用了sassgem,所以我认为搭载会像以下一样简单:classRectangleincludeSass::Script::FunctionsdefcolorSass::Script::Color.new([0x82,0x39,0x06])enddefrender#hamlengineexecutedwithcontextofself#sothatwithintemlateicouldcall#%stop{offset:'0%',stop:{color:lighten(color)}}endend更新:参见上面的#re
我有一个具有一些属性的模型:attr1、attr2和attr3。我需要在不执行回调和验证的情况下更新此属性。我找到了update_column方法,但我想同时更新三个属性。我需要这样的东西:update_columns({attr1:val1,attr2:val2,attr3:val3})代替update_column(attr1,val1)update_column(attr2,val2)update_column(attr3,val3) 最佳答案 您可以使用update_columns(attr1:val1,attr2:val2