Java collections
Java collection
// Convert List to Set
List<String> numbers1 = Arrays.asList("1", "2", "3", "4", "5", "6");
System.out.println("Output1:" + numbers1.toString());
Set<String> numbers2 = numbers.stream().collect(Collectors.toSet());
System.out.println("Output2:" + numbers2.toString());
Output1:[1, 2, 3, 4, 5, 6]
Output2:[1, 2, 3, 4, 5, 6]
Example of stream, map, filter and collect
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class ListTest {
public static void main(String args[]) {
List<String> numbers = Arrays.asList("1", "2", "3", "4", "5", "6");
System.out.println("original list: " + numbers);
List<Integer> even = numbers.stream()
.map(s -> Integer.valueOf(s))
.filter(number -> number % 2 == 0)
.collect(Collectors.toList());
System.out.println("processed list, only even numbers: " + even);
}
}
Result:
original list: [1, 2, 3, 4, 5, 6]
processed list, only even numbers: [2, 4, 6]
Leave a comment