在Java中聯接和折開數組和集合

1.概述

在本快速教程中,我們將學習如何充分利用新的流支持來使用Java連接和拆分數組集合**。

2.連接兩個數組

讓我們開始使用Stream.concat將兩個數組連接在一起

@Test

 public void whenJoiningTwoArrays_thenJoined() {

 String[] animals1 = new String[] { "Dog", "Cat" };

 String[] animals2 = new String[] { "Bird", "Cow" };



 String[] result = Stream.concat(

 Arrays.stream(animals1), Arrays.stream(animals2)).toArray(String[]::new);



 assertArrayEquals(result, new String[] { "Dog", "Cat", "Bird", "Cow" });

 }

3.加入兩個收藏

讓我們對兩個集合進行相同的聯接

@Test

 public void whenJoiningTwoCollections_thenJoined() {

 Collection<String> collection1 = Arrays.asList("Dog", "Cat");

 Collection<String> collection2 = Arrays.asList("Bird", "Cow", "Moose");



 Collection<String> result = Stream.concat(

 collection1.stream(), collection2.stream())

 .collect(Collectors.toList());



 assertTrue(result.equals(Arrays.asList("Dog", "Cat", "Bird", "Cow", "Moose")));

 }

4.通過過濾器加入兩個集合

現在,讓我們加入兩個大於10的數字集合

@Test

 public void whenJoiningTwoCollectionsWithFilter_thenJoined() {

 Collection<String> collection1 = Arrays.asList("Dog", "Cat");

 Collection<String> collection2 = Arrays.asList("Bird", "Cow", "Moose");



 Collection<String> result = Stream.concat(

 collection1.stream(), collection2.stream())

 .filter(e -> e.length() == 3)

 .collect(Collectors.toList());



 assertTrue(result.equals(Arrays.asList("Dog", "Cat", "Cow")));

 }

5.將數組連接字符串

接下來,讓我們使用收集器將數組連接到字符串中**:

@Test

 public void whenConvertArrayToString_thenConverted() {

 String[] animals = new String[] { "Dog", "Cat", "Bird", "Cow" };

 String result = Arrays.stream(animals).collect(Collectors.joining(", "));



 assertEquals(result, "Dog, Cat, Bird, Cow");

 }

6.將集合加入字符串

讓我們做同樣的事情,但是使用Collection

@Test

 public void whenConvertCollectionToString_thenConverted() {

 Collection<String> animals = Arrays.asList("Dog", "Cat", "Bird", "Cow");

 String result = animals.stream().collect(Collectors.joining(", "));



 assertEquals(result, "Dog, Cat, Bird, Cow");

 }

7.將映射加入字符串

接下來,讓我們從Map中創建一個String

該過程與前面的示例非常相似,但是在這裡,我們還有一個額外的步驟來首先加入每個Map Entry

@Test

 public void whenConvertMapToString_thenConverted() {

 Map<Integer, String> animals = new HashMap<>();

 animals.put(1, "Dog");

 animals.put(2, "Cat");

 animals.put(3, "Cow");



 String result = animals.entrySet().stream()

 .map(entry -> entry.getKey() + " = " + entry.getValue())

 .collect(Collectors.joining(", "));



 assertEquals(result, "1 = Dog, 2 = Cat, 3 = Cow");

 }

8.將嵌套集合加入字符串

讓我們做一些更複雜的事情。讓我們將一些嵌套Collections連接String中

在下面的示例中,我們首先在每個嵌套的Collection中進行聯接,然後對它們各自的結果進行聯接:

@Test

 public void whenConvertNestedCollectionToString_thenConverted() {

 Collection<List<String>> nested = new ArrayList<>();

 nested.add(Arrays.asList("Dog", "Cat"));

 nested.add(Arrays.asList("Cow", "Pig"));



 String result = nested.stream().map(

 nextList -> nextList.stream()

 .collect(Collectors.joining("-")))

 .collect(Collectors.joining("; "));



 assertEquals(result, "Dog-Cat; Cow-Pig");

 }

9.加入時處理

免得看到我們如何使用過濾器跳過任何值:

@Test

 public void whenConvertCollectionToStringAndSkipNull_thenConverted() {

 Collection<String> animals = Arrays.asList("Dog", "Cat", null, "Moose");

 String result = animals.stream()

 .filter(Objects::nonNull)

 .collect(Collectors.joining(", "));



 assertEquals(result, "Dog, Cat, Moose");

 }

10.將集合一分為二

讓我們在中間將數字集合拆分為兩個集合

@Test

 public void whenSplitCollectionHalf_thenConverted() {

 Collection<String> animals = Arrays.asList(

 "Dog", "Cat", "Cow", "Bird", "Moose", "Pig");

 Collection<String> result1 = new ArrayList<>();

 Collection<String> result2 = new ArrayList<>();

 AtomicInteger count = new AtomicInteger();

 int midpoint = Math.round(animals.size() / 2);



 animals.forEach(next -> {

 int index = count.getAndIncrement();

 if (index < midpoint) {

 result1.add(next);

 } else {

 result2.add(next);

 }

 });



 assertTrue(result1.equals(Arrays.asList("Dog", "Cat", "Cow")));

 assertTrue(result2.equals(Arrays.asList("Bird", "Moose", "Pig")));

 }

11.按字長分割數組

接下來,讓我們按單詞的長度拆分數組:

@Test

 public void whenSplitArrayByWordLength_thenConverted() {

 String[] animals = new String[] { "Dog", "Cat", "Bird", "Cow", "Pig", "Moose"};

 Map<Integer, List<String>> result = Arrays.stream(animals)

 .collect(Collectors.groupingBy(String::length));



 assertTrue(result.get(3).equals(Arrays.asList("Dog", "Cat", "Cow", "Pig")));

 assertTrue(result.get(4).equals(Arrays.asList("Bird")));

 assertTrue(result.get(5).equals(Arrays.asList("Moose")));

 }

12.將字符串拆分為數組

現在讓我們做相反的事情,讓我們將String拆分為Array:

@Test

 public void whenConvertStringToArray_thenConverted() {

 String animals = "Dog, Cat, Bird, Cow";

 String[] result = animals.split(", ");



 assertArrayEquals(result, new String[] { "Dog", "Cat", "Bird", "Cow" });

 }

13.將字符串拆分為一個集合

此示例與上一個示例相似,僅需一個額外的步驟即可將Array轉換為Collection

@Test

 public void whenConvertStringToCollection_thenConverted() {

 String animals = "Dog, Cat, Bird, Cow";

 Collection<String> result = Arrays.asList(animals.split(", "));



 assertTrue(result.equals(Arrays.asList("Dog", "Cat", "Bird", "Cow")));

 }

14.將字符串拆分為映射

現在,讓我們從String創建一個Map 。我們將需要將字符串拆分兩次,每次輸入一次,最後一次拆分鍵和值:

@Test

 public void whenConvertStringToMap_thenConverted() {

 String animals = "1 = Dog, 2 = Cat, 3 = Bird";



 Map<Integer, String> result = Arrays.stream(

 animals.split(", ")).map(next -> next.split(" = "))

 .collect(Collectors.toMap(entry -> Integer.parseInt(entry[0]), entry -> entry[1]));



 assertEquals(result.get(1), "Dog");

 assertEquals(result.get(2), "Cat");

 assertEquals(result.get(3), "Bird");

 }

15.帶多個分隔符的分割字符串

最後,讓我們使用正則表達式拆分具有多個分隔符的String ,我們還將刪除所有空結果:

@Test

 public void whenConvertCollectionToStringMultipleSeparators_thenConverted() {

 String animals = "Dog. , Cat, Bird. Cow";



 Collection<String> result = Arrays.stream(animals.split("[,|.]"))

 .map(String::trim)

 .filter(next -> !next.isEmpty())

 .collect(Collectors.toList());



 assertTrue(result.equals(Arrays.asList("Dog", "Cat", "Bird", "Cow")));

 }

16.結論

在本教程中,利用簡單的String.split函數和強大的Java 8 Stream,我們說明瞭如何联接和拆分數組集合。

您可以在GitHub上找到本文的代碼。