21 Star 83 Fork 16

sd4324530/JTuple

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
贡献代码
同步代码
取消
提示: 由于 Git 不支持空文件夾,创建文件夹后会生成空的 .keep 文件
Loading...
README
Apache-2.0

JTuple

@peiyu on weibo Maven Central JDK 1.8 Circle CI codecov License

java语言版本的元组数据类型,实现了元组类型的特性(不可变可迭代)以及常用操作方法

轻量级,无依赖,线程安全

元组的意义

元组最重要的意义是用来实现多值返现。 很多时候我们需要返回一组值,更可怕的是这组值的类型可能并不完全一样,比如http请求时,有请求的返回码(int)以及响应报文(String)

对于java人员来说,遇到这种情况时,一般的解决方案是编写一个类,类里只有2个属性,分别是以上2个,然后返回给调用者。是不是有种胸闷的感觉。折腾,造孽啊

或者就返回一个列表,但是因为类型不统一,只能用List<Object>,后续处理的代码的可读性会很差,我相信任何一个技术水平过关或者有职业操守的程序员都不会这么做

元组的出现,就是为了解决这种情况的,很多年轻的语言(Python, Scala...)都内置了元组,本项目就是让Java开发人员也可以享受到元组带来的编程时的便捷和快乐

主要实现

类名 描述
Tuple 元组抽象,实现元组数据结构以及常用操作方法
Tuple0 空元组,不包含任何元素
Tuple1 只包含1个元素的元组
Tuple2 只包含2个元素的元组
Tuple3 只包含3个元素的元组
Tuple4 只包含4个元素的元组
Tuple5 只包含5个元素的元组
TupleN 包含N个元素的元组
Tuples 提供优雅使用元组方式的工具类

元组操作

操作API 说明
add 元组合并
foreach 元组迭代
forEachWithIndex 元组带序号迭代
reverse 元组翻转
toArray 元组转成数组
toList 元组转成列表
get 获取元组某一个元素
contains 元组中是否包含某个元素
subTuple 截取子元组
equals 比较2个元组内容是否相同
toString 输出字符串表示的元组,如: (123, 456)
repeat 重复元组内的所有元素
stream 将元组转换成流,类似List.stream
parallelStream 将元组转换成并行流,类似List.parallelStream
sort 将元组列表(数组)进行排序

API使用样例

//静态导入工具类,然后开始优雅的使用元组吧
import static com.github.sd4324530.jtuple.Tuples.tuple;
//读取指定位置元素
Tuple2<String, Integer> tuple = tuple("test", 123);
log.debug("first:{}", tuple2.first);//test
log.debug("second:{}", tuple2.second);//123
//toString
Tuple4<String, Integer, Boolean, Double> tuple = tuple("test", 123, true, 186.5);
log.debug("tuple4:{}", tuple.toString());//(test, 123, true, 186.5)
//元组遍历
Tuple5<String, Integer, Boolean, Double, Character> tuple = tuple("test", 123, true, 186.5, 'A');
//方式1
tuple.forEach(o -> log.debug(Objects.toString(o)));
//方式2
for (Object object : tuple) {
  log.debug(Objects.toString(object));
}
//元组合并
Tuple1<String> tuple1 = tuple("hello");
Tuple2<String, String> tuple2 = tuple("world", "!");
Tuple3<Integer, Integer, Integer> tuple3 = tuple(1, 2, 3);
log.debug("add:{}", tuple1.add(tuple2).toString());//(hello, world, !)
log.debug("add:{}", tuple1.add(tuple2, tuple3).toString());//(hello, world, !, 1, 2, 3)
//元组翻转
Tuple4<String, Integer, Boolean, Double> tuple = tuple("hello", 123, true, 186.5);
log.debug("reverse:{}", tuple.reverse().toString());//(186.5, true, 123, hello)
//元组重复
Tuple2<String, String> tuple2 = tuple("a", "b");
log.debug("repeat:{}", tuple2.repeat(3).toString());//(a, b, a, b, a, b)
//截取子元组
TupleN tupleN = tuple(0, 1, 2, 3, 4, 5, 6);
log.debug("sub:{}", tupleN.subTuple(0, 3).toString());//(0, 1, 2, 3)
//转换成流
Tuple5<String, Integer, Boolean, Object, Double> tuple5 = tuple("hello", 123, true, null, 186.5);
tuple5.stream().forEach(o -> log.debug("元素:{}", o));
//元组列表排序
//静态导入工具类
import static com.github.sd4324530.jtuple.Tuples.tuple;
import static com.github.sd4324530.jtuple.Tuples.sort;

List<Tuple2> list = new ArrayList<>();
list.add(tuple(5, "5"));
list.add(tuple(2, "2"));
list.add(tuple(3, "3"));
list.add(tuple(1, "1"));
list.add(tuple(4, "4"));
log.debug("before:{}", list);
//按第一列Integer类型升序
sort(list, 0, Integer::compare);
log.debug("after:{}", list);//1, 2, 3, 4, 5
//元组数组排序
//静态导入工具类
import static com.github.sd4324530.jtuple.Tuples.tuple;
import static com.github.sd4324530.jtuple.Tuples.sort;

Tuple2[] array = new Tuple2[5];
array[0] = tuple("5", 5);
array[1] = tuple("2", 2);
array[2] = tuple("3", 3);
array[3] = tuple("1", 1);
array[4] = tuple("4", 4);
log.debug("before:{}", Arrays.toString(array));
//按第一列String类型升序
sort(array, 0, String::compareTo);
log.debug("after:{}", Arrays.toString(array));

元组使用场景样例

  1. http请求封装

    public class HttpKit {
    
        /**
         * http get 请求
         *
         * @param url 请求url
         * @return 请求结果元组,第一个元素为请求返回码,第二个参数为返回内容,第三个参数为请求失败时的异常
         */
        public Tuple3<Integer, String, Exception> get(String url) {
            //发送请求,解析结果
            return null;
        }
    }

  2. 数据库操作封装

    public class DbKit {
    
      import static com.github.sd4324530.jtuple.Tuples.tuple;
        /**
         * 执行查询sql
         *
         * @param sql 查询sql
         * @return 执行结果元组,第一个元素用来判断执行是否出现异常,如果为null,则表示成功;第二个参数为查询结果
         */
        public Tuple2<Exception, List<Object>> query(String sql) {
            try (Connection connection = getConn(); Statement statement = connection.createStatement(); ResultSet resultSet = statement.executeQuery(sql)) {
                List<Object> data = handleResult(resultSet);
                return tuple(null, data);
            } catch (Exception e) {
                return tuple(e, null);
            }
        }
    }

引入(jdk >= 1.8)

<dependency>
     <groupId>com.github.sd4324530</groupId>
     <artifactId>JTuple</artifactId>
     <version>1.2.1</version>
</dependency>
Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: You must give any other recipients of the Work or Derivative Works a copy of this License; and You must cause any modified files to carry prominent notices stating that You changed the files; and You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "{}" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright 2016 sd4324530 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.

简介

java语言版本的`元组`数据类型,实现了元组类型的特性以及常用操作方法 展开 收起
Java
Apache-2.0
取消

发行版

暂无发行版

贡献者

全部

近期动态

加载更多
不能加载更多了
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Java
1
https://gitee.com/pyinjava/jtuple.git
git@gitee.com:pyinjava/jtuple.git
pyinjava
jtuple
JTuple
master

搜索帮助