com.github.steveash.jg2p.util.Zipper Maven / Gradle / Ivy
The newest version!
/*
* Copyright 2014 Steve Ash
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.steveash.jg2p.util;
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.commons.lang3.tuple.Pair;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
/**
* @author Steve Ash
*/
public class Zipper {
public static Map toMap(Iterable a, Iterable b) {
Map result = Maps.newHashMap();
Iterator iterA = a.iterator();
Iterator iterB = b.iterator();
while (iterA.hasNext()) {
Preconditions.checkArgument(iterB.hasNext(), "B is shorter than A, must be same size");
A aa = iterA.next();
B bb = iterB.next();
result.put(aa, bb);
}
Preconditions.checkArgument(!iterB.hasNext(), "A is shorter than B, must be same size");
return result;
}
public static List> up(Iterable a, Iterable b) {
ArrayList> result = Lists.newArrayList();
Iterator iterA = a.iterator();
Iterator iterB = b.iterator();
while (iterA.hasNext()) {
Preconditions.checkArgument(iterB.hasNext(), "B is shorter than A, must be same size");
A aa = iterA.next();
B bb = iterB.next();
result.add(Pair.of(aa, bb));
}
Preconditions.checkArgument(!iterB.hasNext(), "A is shorter than B, must be same size");
return result;
}
public static List> upTo(Iterable a, B b) {
ArrayList> result = Lists.newArrayList();
for (A aa : a) {
result.add(Pair.of(aa, b));
}
return result;
}
public static List> upTo(A a, Iterable b) {
ArrayList> result = Lists.newArrayList();
for (B bb : b) {
result.add(Pair.of(a, bb));
}
return result;
}
public static List> replaceRight(List> original, Iterable newRight) {
ArrayList> result = Lists.newArrayListWithCapacity(original.size());
Iterator iter = newRight.iterator();
for (Pair pair : original) {
Preconditions.checkArgument(iter.hasNext(), "newRight is smaller than original");
result.add(Pair.of(pair.getLeft(), iter.next()));
}
Preconditions.checkArgument(!iter.hasNext(), "newRight is bigger than original");
return result;
}
}