Guest User

Untitled

a guest
Nov 20th, 2017
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 13.11 KB | None | 0 0
  1. List<Person> beerDrinkers = persons.stream()
  2. .filter(p -> p.getAge() > 16).collect(Collectors.toList());
  3.  
  4. persons.removeIf(p -> p.getAge() <= 16);
  5.  
  6. List<Person> beerDrinkers = select(persons, having(on(Person.class).getAge(),
  7. greaterThan(16)));
  8.  
  9. public interface IPredicate<T> { boolean apply(T type); }
  10.  
  11. public static <T> Collection<T> filter(Collection<T> target, IPredicate<T> predicate) {
  12. Collection<T> result = new ArrayList<T>();
  13. for (T element: target) {
  14. if (predicate.apply(element)) {
  15. result.add(element);
  16. }
  17. }
  18. return result;
  19. }
  20.  
  21. Predicate<User> isAuthorized = new Predicate<User>() {
  22. public boolean apply(User user) {
  23. // binds a boolean method in User to a reference
  24. return user.isAuthorized();
  25. }
  26. };
  27. // allUsers is a Collection<User>
  28. Collection<User> authorizedUsers = filter(allUsers, isAuthorized);
  29.  
  30. public class Predicate {
  31. public static Object predicateParams;
  32.  
  33. public static <T> Collection<T> filter(Collection<T> target, IPredicate<T> predicate) {
  34. Collection<T> result = new ArrayList<T>();
  35. for (T element : target) {
  36. if (predicate.apply(element)) {
  37. result.add(element);
  38. }
  39. }
  40. return result;
  41. }
  42.  
  43. public static <T> T select(Collection<T> target, IPredicate<T> predicate) {
  44. T result = null;
  45. for (T element : target) {
  46. if (!predicate.apply(element))
  47. continue;
  48. result = element;
  49. break;
  50. }
  51. return result;
  52. }
  53.  
  54. public static <T> T select(Collection<T> target, IPredicate<T> predicate, T defaultValue) {
  55. T result = defaultValue;
  56. for (T element : target) {
  57. if (!predicate.apply(element))
  58. continue;
  59. result = element;
  60. break;
  61. }
  62. return result;
  63. }
  64. }
  65.  
  66. List<MyTypeA> missingObjects = (List<MyTypeA>) Predicate.filter(myCollectionOfA,
  67. new IPredicate<MyTypeA>() {
  68. public boolean apply(MyTypeA objectOfA) {
  69. Predicate.predicateParams = objectOfA.getName();
  70. return Predicate.select(myCollectionB, new IPredicate<MyTypeB>() {
  71. public boolean apply(MyTypeB objectOfB) {
  72. return objectOfB.getName().equals(Predicate.predicateParams.toString());
  73. }
  74. }) == null;
  75. }
  76. });
  77.  
  78. MyType myObject = Predicate.select(collectionOfMyType, new IPredicate<MyType>() {
  79. public boolean apply(MyType objectOfMyType) {
  80. return objectOfMyType.isDefault();
  81. }}, collectionOfMyType.get(0));
  82.  
  83. final UserService userService = ... // perhaps injected IoC
  84. final Optional<UserModel> userOption = userCollection.stream().filter(u -> {
  85. boolean isAuthorized = userService.isAuthorized(u);
  86. return isAuthorized;
  87. }).findFirst();
  88.  
  89. final UserService userService = ... // perhaps injected IoC
  90. final List<UserModel> userOption = userCollection.stream().filter(u -> {
  91. boolean isAuthorized = userService.isAuthorized(u);
  92. return isAuthorized;
  93. }).collect(Collectors.toList());
  94.  
  95. Iterator<Foo> it = col.iterator();
  96. while( it.hasNext() ) {
  97. Foo foo = it.next();
  98. if( !condition(foo) ) it.remove();
  99. }
  100.  
  101. CollectionUtils.filterInPlace(col,
  102. new IPredicate<Foo>(){
  103. public boolean keepIt(Foo foo) {
  104. return foo.isBar();
  105. }
  106. });
  107.  
  108. List<Person> olderThan30 =
  109. //Create a Stream from the personList
  110. personList.stream().
  111. //filter the element to select only those with age >= 30
  112. filter(p -> p.age >= 30).
  113. //put those filtered elements into a new List.
  114. collect(Collectors.toList());
  115.  
  116. Collection<T> collection = ...;
  117. Stream<T> stream = collection.stream().filter(...);
  118.  
  119. List<Integer> numbers = Arrays.asList(12, 74, 5, 8, 16);
  120. numbers.stream().filter(n -> n > 10).forEach(System.out::println);
  121.  
  122. Observable.from(Arrays.asList(1, 2, 3, 4, 5))
  123. .filter(new Func1<Integer, Boolean>() {
  124. public Boolean call(Integer i) {
  125. return i % 2 != 0;
  126. }
  127. })
  128. .subscribe(new Action1<Integer>() {
  129. public void call(Integer i) {
  130. System.out.println(i);
  131. }
  132. });
  133.  
  134. 1
  135. 3
  136. 5
  137.  
  138. public interface Predicate<T> {
  139. public boolean filter(T t);
  140. }
  141.  
  142. void filterCollection(Collection<T> col, Predicate<T> predicate) {
  143. for (Iterator i = col.iterator(); i.hasNext();) {
  144. T obj = i.next();
  145. if (predicate.filter(obj)) {
  146. i.remove();
  147. }
  148. }
  149. }
  150.  
  151. List<MyObject> myList = ...;
  152. filterCollection(myList, new Predicate<MyObject>() {
  153. public boolean filter(MyObject obj) {
  154. return obj.shouldFilter();
  155. }
  156. });
  157.  
  158. List<Integer> jdkList = Arrays.asList(1, 2, 3, 4, 5);
  159. MutableList<Integer> ecList = Lists.mutable.with(1, 2, 3, 4, 5);
  160.  
  161. List<Integer> selected = Lists.mutable.with(1, 2);
  162. List<Integer> rejected = Lists.mutable.with(3, 4, 5);
  163.  
  164. Predicate<Integer> lessThan3 = new Predicate<Integer>()
  165. {
  166. public boolean accept(Integer each)
  167. {
  168. return each < 3;
  169. }
  170. };
  171.  
  172. Assert.assertEquals(selected, Iterate.select(jdkList, lessThan3));
  173.  
  174. Assert.assertEquals(selected, ecList.select(lessThan3));
  175.  
  176. Assert.assertEquals(selected, Iterate.select(jdkList, Predicates.lessThan(3)));
  177.  
  178. Assert.assertEquals(selected, ecList.select(Predicates.lessThan(3)));
  179.  
  180. Assert.assertEquals(
  181. selected, ecList.selectWith(Predicates2.<Integer>lessThan(), 3));
  182.  
  183. Assert.assertEquals(rejected, Iterate.reject(jdkList, lessThan3));
  184.  
  185. Assert.assertEquals(rejected, ecList.reject(lessThan3));
  186.  
  187. Assert.assertEquals(selected, Iterate.select(jdkList, each -> each < 3));
  188. Assert.assertEquals(rejected, Iterate.reject(jdkList, each -> each < 3));
  189.  
  190. Assert.assertEquals(selected, gscList.select(each -> each < 3));
  191. Assert.assertEquals(rejected, gscList.reject(each -> each < 3));
  192.  
  193. PartitionIterable<Integer> jdkPartitioned = Iterate.partition(jdkList, lessThan3);
  194. Assert.assertEquals(selected, jdkPartitioned.getSelected());
  195. Assert.assertEquals(rejected, jdkPartitioned.getRejected());
  196.  
  197. PartitionList<Integer> ecPartitioned = gscList.partition(lessThan3);
  198. Assert.assertEquals(selected, ecPartitioned.getSelected());
  199. Assert.assertEquals(rejected, ecPartitioned.getRejected());
  200.  
  201. import static ch.akuhn.util.query.Query.select;
  202. import static ch.akuhn.util.query.Query.$result;
  203. import ch.akuhn.util.query.Select;
  204.  
  205. Collection<String> collection = ...
  206.  
  207. for (Select<String> each : select(collection)) {
  208. each.yield = each.value.length() > 3;
  209. }
  210.  
  211. Collection<String> result = $result();
  212.  
  213. List<Customer> list ...;
  214. List<Customer> newList = new ArrayList<>();
  215. for (Customer c : list){
  216. if (c.getName().equals("dd")) newList.add(c);
  217. }
  218.  
  219. List<Customer> newList = list.stream().filter(c -> c.getName().equals("dd")).collect(toList());
  220.  
  221. LinkedList<Person> list = ......
  222. LinkedList<Person> filtered =
  223. Query.from(list).where(Condition.ensure("age", Op.GTE, 21));
  224.  
  225. LinkedList<Person> list = ....
  226. LinkedList<Person> filtered = Query.from(list).where("x => x.age >= 21");
  227.  
  228. List<Integer> myList = new ArrayList<Integer>(){ 1, 2, 3, 4, 5 }
  229.  
  230. Iterable<Integer> filtered = Iterable.wrap(myList).select(new Predicate1<Integer>()
  231. {
  232. public Boolean call(Integer n) throws FunctionalException
  233. {
  234. return n % 2 == 0;
  235. }
  236. })
  237.  
  238. for( int n : filtered )
  239. {
  240. System.out.println(n);
  241. }
  242.  
  243. for( int n : myList )
  244. {
  245. if( n % 2 == 0 )
  246. {
  247. System.out.println(n);
  248. }
  249. }
  250.  
  251. ArrayList<Item> filtered = new ArrayList<Item>();
  252. for (Item item : items) if (condition(item)) filtered.add(item);
  253.  
  254. Collection<Dto> testList = new ArrayList<>();
  255.  
  256. class Dto
  257. {
  258. private int id;
  259. private String text;
  260.  
  261. public int getId()
  262. {
  263. return id;
  264. }
  265.  
  266. public int getText()
  267. {
  268. return text;
  269. }
  270. }
  271.  
  272. Filter<Dto> query = CQ.<Dto>filter(testList)
  273. .where()
  274. .property("id").eq().value(1);
  275. Collection<Dto> filtered = query.list();
  276.  
  277. Filter<Dto> query = CQ.<Dto>filter(testList)
  278. .where()
  279. .property(Dto::getId)
  280. .eq().value(1);
  281. Collection<Dto> filtered = query.list();
  282.  
  283. Filter<Dto> query = CQ.<Dto>filter()
  284. .from(testList)
  285. .where()
  286. .property(Dto::getId).between().value(1).value(2)
  287. .and()
  288. .property(Dto::grtText).in().value(new string[]{"a","b"});
  289.  
  290. Filter<Dto> query = CQ.<Dto>filter(testList)
  291. .orderBy()
  292. .property(Dto::getId)
  293. .property(Dto::getName)
  294. Collection<Dto> sorted = query.list();
  295.  
  296. GroupQuery<Integer,Dto> query = CQ.<Dto,Dto>query(testList)
  297. .group()
  298. .groupBy(Dto::getId)
  299. Collection<Grouping<Integer,Dto>> grouped = query.list();
  300.  
  301. class LeftDto
  302. {
  303. private int id;
  304. private String text;
  305.  
  306. public int getId()
  307. {
  308. return id;
  309. }
  310.  
  311. public int getText()
  312. {
  313. return text;
  314. }
  315. }
  316.  
  317. class RightDto
  318. {
  319. private int id;
  320. private int leftId;
  321. private String text;
  322.  
  323. public int getId()
  324. {
  325. return id;
  326. }
  327.  
  328. public int getLeftId()
  329. {
  330. return leftId;
  331. }
  332.  
  333. public int getText()
  334. {
  335. return text;
  336. }
  337. }
  338.  
  339. class JoinedDto
  340. {
  341. private int leftId;
  342. private int rightId;
  343. private String text;
  344.  
  345. public JoinedDto(int leftId,int rightId,String text)
  346. {
  347. this.leftId = leftId;
  348. this.rightId = rightId;
  349. this.text = text;
  350. }
  351.  
  352. public int getLeftId()
  353. {
  354. return leftId;
  355. }
  356.  
  357. public int getRightId()
  358. {
  359. return rightId;
  360. }
  361.  
  362. public int getText()
  363. {
  364. return text;
  365. }
  366. }
  367.  
  368. Collection<LeftDto> leftList = new ArrayList<>();
  369.  
  370. Collection<RightDto> rightList = new ArrayList<>();
  371.  
  372. Collection<JoinedDto> results = CQ.<LeftDto, LeftDto>query().from(leftList)
  373. .<RightDto, JoinedDto>innerJoin(CQ.<RightDto, RightDto>query().from(rightList))
  374. .on(LeftFyo::getId, RightDto::getLeftId)
  375. .transformDirect(selection -> new JoinedDto(selection.getLeft().getText()
  376. , selection.getLeft().getId()
  377. , selection.getRight().getId())
  378. )
  379. .list();
  380.  
  381. Filter<Dto> query = CQ.<Dto>filter()
  382. .from(testList)
  383. .where()
  384. .exec(s -> s.getId() + 1).eq().value(2);
  385.  
  386. public abstract class AbstractFilter<T> {
  387.  
  388. /**
  389. * Method that returns whether an item is to be included or not.
  390. * @param item an item from the given collection.
  391. * @return true if this item is to be included in the collection, false in case it has to be removed.
  392. */
  393. protected abstract boolean excludeItem(T item);
  394.  
  395. public void filter(Collection<T> collection) {
  396. if (CollectionUtils.isNotEmpty(collection)) {
  397. Iterator<T> iterator = collection.iterator();
  398. while (iterator.hasNext()) {
  399. if (excludeItem(iterator.next())) {
  400. iterator.remove();
  401. }
  402. }
  403. }
  404. }
  405.  
  406. CollectionUtils.filter(list, p -> ((Person) p).getAge() > 16);
  407.  
  408. myProducts.stream().filter(prod -> prod.price>10).collect(Collectors.toList())
  409.  
  410. Collection<Integer> collection = Lists.newArrayList(1, 2, 3, 4, 5);
  411.  
  412. Iterators.removeIf(collection.iterator(), new Predicate<Integer>() {
  413. @Override
  414. public boolean apply(Integer i) {
  415. return i % 2 == 0;
  416. }
  417. });
  418.  
  419. System.out.println(collection); // Prints 1, 3, 5
  420.  
  421. public class Filter {
  422. public static <T> void List(List<T> list, Chooser<T> chooser) {
  423. List<Integer> toBeRemoved = new ArrayList<>();
  424. leftloop:
  425. for (int right = 1; right < list.size(); ++right) {
  426. for (int left = 0; left < right; ++left) {
  427. if (toBeRemoved.contains(left)) {
  428. continue;
  429. }
  430. Keep keep = chooser.choose(list.get(left), list.get(right));
  431. switch (keep) {
  432. case LEFT:
  433. toBeRemoved.add(right);
  434. continue leftloop;
  435. case RIGHT:
  436. toBeRemoved.add(left);
  437. break;
  438. case NONE:
  439. toBeRemoved.add(left);
  440. toBeRemoved.add(right);
  441. continue leftloop;
  442. }
  443. }
  444. }
  445.  
  446. Collections.sort(toBeRemoved, new Comparator<Integer>() {
  447. @Override
  448. public int compare(Integer o1, Integer o2) {
  449. return o2 - o1;
  450. }
  451. });
  452.  
  453. for (int i : toBeRemoved) {
  454. if (i >= 0 && i < list.size()) {
  455. list.remove(i);
  456. }
  457. }
  458. }
  459.  
  460. public static <T> void List(List<T> list, Keeper<T> keeper) {
  461. Iterator<T> iterator = list.iterator();
  462. while (iterator.hasNext()) {
  463. if (!keeper.keep(iterator.next())) {
  464. iterator.remove();
  465. }
  466. }
  467. }
  468.  
  469. public interface Keeper<E> {
  470. boolean keep(E obj);
  471. }
  472.  
  473. public interface Chooser<E> {
  474. Keep choose(E left, E right);
  475. }
  476.  
  477. public enum Keep {
  478. LEFT, RIGHT, BOTH, NONE;
  479. }
  480. }
  481.  
  482. List<String> names = new ArrayList<>();
  483. names.add("Anders");
  484. names.add("Stefan");
  485. names.add("Anders");
  486. Filter.List(names, new Filter.Chooser<String>() {
  487. @Override
  488. public Filter.Keep choose(String left, String right) {
  489. return left.equals(right) ? Filter.Keep.LEFT : Filter.Keep.BOTH;
  490. }
  491. });
Add Comment
Please, Sign In to add comment