10 個牛逼的一行代碼就能搞定的編程技巧,你會用嗎?

雲棲號資訊:【點擊查看更多行業資訊
在這裏您可以找到不同行業的第一手的上雲資訊,還在等什麼,快來!

本文列舉了十個使用一行代碼即可獨立完成(不依賴其他代碼)的業務邏輯,主要依賴的是Java8中的Lambda和Stream等新特性以及try-with-resources、JAXB等。

1、對列表/數組中的每個元素都乘以2

 // Range是半開區間
 int [] ia = range(1, 10).map(i -> i * 2).toArray();
 List<Integer> result = range(1, 10).map(i -> i * 2).boxed().collect(toList());

2、計算集合/數組中的數字之和

 range(1, 1000).sum();
 range(1, 1000).reduce(0, Integer::sum);
 Stream.iterate(0, i -> i + 1).limit(1000).reduce(0, Integer::sum);
 IntStream.iterate(0, i -> i + 1).limit(1000).reduce(0, Integer::sum);

3、驗證字符串是否包含集合中的某一字符串

final List<String> keywords = Arrays.asList("brown", "fox", "dog", "pangram");
final String tweet = "The quick brown fox jumps over a lazy dog. #pangram http://www.rinkworks.com/words/pangrams.shtml";

keywords.stream().anyMatch(tweet::contains);
keywords.stream().reduce(false, (b, keyword) -> b || tweet.contains(keyword), (l, r) -> l || r);

4、讀取文件內容

原作者認爲try with resources也是一種單行代碼編程。

try (BufferedReader reader = new BufferedReader(new FileReader("data.txt"))) {
   String fileText = reader.lines().reduce("", String::concat);
 }

 try (BufferedReader reader = new BufferedReader(new FileReader("data.txt"))) {
   List<String> fileLines = reader.lines().collect(toCollection(LinkedList<String>::new));
 }

 try (Stream<String> lines = Files.lines(new File("data.txt").toPath(), Charset.defaultCharset())) {
   List<String> fileLines = lines.collect(toCollection(LinkedList<String>::new));
 }

5、輸出歌曲《Happy Birthday to You!》 - 根據集合中不同的元素輸出不同的字符串

 range(1, 5).boxed().map(i -> { out.print("Happy Birthday "); if (i == 3) return "dear NAME"; else return "to You"; }).for

6、過濾並分組集合中的數字

 Map<String, List<Integer>> result = Stream.of(49, 58, 76, 82, 88, 90).collect(groupingBy(forPredicate(i -> i > 

7、獲取並解析xml協議的Web Service

FeedType feed = JAXB.unmarshal(new URL("http://search.twitter.com/search.atom?&q=java8"), FeedType.class);
JAXB.marshal(feed, System.out);

8、獲得集合中最小/最大的數字

 int min = Stream.of(14, 35, -7, 46, 98).reduce(Integer::min).get();
 min = Stream.of(14, 35, -7, 46, 98).min(Integer::compare).get();
 min = Stream.of(14, 35, -7, 46, 98).mapToInt(Integer::new).min();

 int max = Stream.of(14, 35, -7, 46, 98).reduce(Integer::max).get();
 max = Stream.of(14, 35, -7, 46, 98).max(Integer::compare).get();
 max = Stream.of(14, 35, -7, 46, 98).mapToInt(Integer::new).max();

9、並行處理

 long result = dataList.parallelStream().mapToInt(line -> processItem(line)).sum();

10、集合上的各種查詢(LINQ in Java)

List<Album> albums = Arrays.asList(unapologetic, tailgates, red);

//篩選出至少有一個track評級4分以上的專輯,並按照名稱排序後打印出來。
albums.stream()
  .filter(a -> a.tracks.stream().anyMatch(t -> (t.rating >= 4)))
  .sorted(comparing(album -> album.name))
  .forEach(album -> System.out.println(album.name));

//合併所有專輯的track
List<Track> allTracks = albums.stream()
  .flatMap(album -> album.tracks.stream())
  .collect(toList());

//根據track的評分對所有track分組
Map<Integer, List<Track>> tracksByRating = allTracks.stream()
  .collect(groupingBy(Track::getRating));

【雲棲號在線課堂】每天都有產品技術專家分享!
課程地址:https://yqh.aliyun.com/zhibo

立即加入社羣,與專家面對面,及時瞭解課程最新動態!
【雲棲號在線課堂 社羣】https://c.tb.cn/F3.Z8gvnK

原文發佈時間:2020-07-08
本文作者:颯然Hang
本文來自:“互聯網架構師”,瞭解相關信息可以關注“互聯網架構師

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章