获取List中的一项
List<String> _outingCntry = list.stream().map(OSzItem::getGroup).
collect(Collectors.toList());
获取List中的多项
List<vo> list = new ArrayList<>();
Map<String, String> map = list.stream().collect(
Collectors.toMap(vo::getxxx, vo::getxxx));
按照条件获取List,包括相同项,不同项等
获取两个Array / List 等不相同项是比较繁琐的过程,通常需要设置全局变量,然后通过for语句判断是否相等,同时改变全局变量。全局变量没有变化的项即是不同。
这种方式显得代码啰嗦,不符合自然思考习惯,所有可以借助List的stream来解决,代码相对整洁。
List<SalrCntry> _diff = _amtCntrylist.stream().
filter(ele->!_outCntry.contains(ele.getCntry())).
collect(Collectors.toList());
通过remove去除相同,剩下的是不同
public class FindDifferencesBetweenListsUnitTest { private static final List listOne = Arrays.asList("Jack", "Tom", "Sam", "John", "James", "Jack"); private static final List listTwo = Arrays.asList("Jack", "Daniel", "Sam", "Alan", "James", "George"); }
List<String> differences = new ArrayList<>(listOne); differences.removeAll(listTwo); assertEquals(2, differences.size()); assertThat(differences).containsExactly("Tom", "John");
List<String> differences = listTwo.stream() .filter(element -> !listOne.contains(element)) .collect(Collectors.toList()); assertEquals(3, differences.size()); assertThat(differences).containsExactly("Daniel", "Alan", "George");