⑦. sorted 排序
①. Stream<T> sorted():返回由此流的元素组成的流,根据自然顺序排序
②. Stream<T> sorted(Comparator comparator):返回由该流的元素组成的流,根据提供的Comparator进行排序Comparator接口中的方法 int compare(T o1, T o2)
public class StreamDemo04 { public static void main(String[] args) { //创建一个集合,存储多个字符串元素 ArrayList<String> list = new ArrayList<String>(); list.add("linqingxia"); list.add("zhangmanyu"); list.add("wangzuxian"); list.add("liuyan"); list.add("zhangmin"); list.add("zhangwuji"); //需求1:按照字母顺序把数据在控制台输出 sorted()是正序 // list.stream().sorted().forEach(System.out::println); //需求2:按照字符串长度把数据在控制台输出 // list.stream().sorted((s1, s2) -> s1.length() - s2.length()).forEach(System.out::println); list.stream().sorted((s1,s2) -> { int num = s1.length()-s2.length(); int num2 = num==0?s1.compareTo(s2):num; return num2; }).forEach(System.out::println); } }
⑧. collect
①. toList:将流中的元素放置到一个列表集合中去。这个列表默认为ArrayList
②. toSet:将流中的元素放置到一个无序集set中去。默认为HashSet。
③. joining:joining的目的是将流中的元素全部以字符序列的方式连接到一起,可以指定连接符,甚至是结果的前后缀
public class CollectorsTest { public static void toListTest(List<String> list) { List<String> ll = list.stream().collect(Collectors.toList()); } public static void main(String[] args) { List<String> list = Arrays.asList("123","456","789","1101","212121121","asdaa","3e3e3e","2321eew"); toListTest(list); } } public class CollectorsTest { public static void toSetTest(List<String> list) { Set<String> ss = list.stream().collect(Collectors.toSet()); } public static void main(String[] args) { List<String> list = Arrays.asList("123","456","789","1101","212121121","asdaa","3e3e3e","2321eew"); toSetTest(list); } } public class CollectorsTest { public static void joiningTest(List<String> list){ // 无参方法 String s = list.stream().collect(Collectors.joining()); System.out.println(s); // 指定连接符 String ss = list.stream().collect(Collectors.joining("-")); System.out.println(ss); // 指定连接符和前后缀 String sss = list.stream().collect(Collectors.joining("-","S","E")); System.out.println(sss); } public static void main(String[] args) { List<String> list = Arrays.asList("123","456","789","1101","212121121","asdaa","3e3e3e","2321eew"); joiningTest(list); } } /* 1234567891101212121121asdaa3e3e3e2321eew 123-456-789-1101-212121121-asdaa-3e3e3e-2321eew S123-456-789-1101-212121121-asdaa-3e3e3e-2321eewE */
⑨. 题目实战
/** * @Description: 题目:请按照给出数据,找出同时满足以下条件的用户,也即以下条件全部满足 * 偶数ID且年龄大于24且用户名转为大写且用户名字母倒排序 只输出一个用户名字 */ public class StreamDemo { public static void main(String[] args) { User u1 = new User(11, "a", 23); User u2 = new User(12, "b", 24); User u3 = new User(13, "c", 22); User u4 = new User(14, "d", 28); User u5 = new User(16, "e", 26); List<User> list = Arrays.asList(u1, u2, u3, u4, u5); list.stream() .filter(s->s.getId()%2==0) .filter(s->s.getAge()>24) .map(s->s.getUserName().toUpperCase()) .sorted((s1,s2)->s2.compareTo(s1)) .limit(1) .forEach(System.out::print); } }