Given :
List<Integer> a = Arrays.asList(1,2,3);
List<Integer> b = Arrays.asList(1,2,3);
List<Integer> c = Arrays.asList(1,2,3);
List<Integer> d = Arrays.asList(1,2,3);
List<List<Integer>> sample = Arrays.asList(a,b,c,d);
How can I get this result with java 8?
[(1,1,1,1),(2,2,2,2),(3,3,3,3)]
1. The addAll() method to merge two lists. The addAll() method is the simplest and most common way to merge two lists. Note the order of appearance of elements matches the order in which addAll() is called.
java. util. zip. ZipOutputStream can be used to compress a file into ZIP format.
Get the name for the zip file to be created. Create a FileOutputStream object for the given zip name. Create a new ZipOutputStream object using the FileOutputStream object. Read the provided file and use the putNextEntry and write methods to add that file to the ZipOutputStream object.
A stream is a sequence of objects that supports various methods which can be pipelined to produce the desired result. The features of Java stream are – A stream is not a data structure instead it takes input from the Collections, Arrays or I/O channels.
/**
* Zips lists. E.g. given [[1,2,3],[4,5,6]], returns [[1,4],[2,5],[3,6]].
* @param listOfLists an N x M list
* @returns an M x N list
*/
static <T> List<List<T>> zip(List<List<T>> listOfLists) {
int size = listOfLists.get(0).size();
List<List<T>> result = new ArrayList<>(size);
for (int i = 0; i < size; ++i)
result.add(
listOfLists.stream()
.map(list -> list.get(i))
.collect(toList()));
return result;
}
Java streams don't natively support zipping.
If you want to do it manually, then using an IntStream as an 'iterator' over the lists is the way to go:
List<Integer> l1 = Arrays.asList(1, 2, 3);
List<Integer> l2 = Arrays.asList(2, 3, 4);
List<Object[]> zipped = IntStream.range(0, 3).mapToObj(i -> new Object[]{l1.get(i), l2.get(i)}).collect(Collectors.toList());
zipped.stream().forEach(i -> System.out.println(i[0] + " " + i[1]));
This is ugly, however, and not the 'java' way (as in using an array of 'properties' instead of a class).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With